how post props redux React - javascript

I would like to explain my problem of the day.
I can't post "this.props.total",
I do not understand how to post a props, can you help me pls?
currently the props works correctly.
import React, { Component } from 'react';
import { CardText, } from 'reactstrap';
import { connect } from 'react-redux'
class thisPropsFortotal extends Component {
handleSubmit = (e) => {
e.preventDefault();
const config = {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({this.props.total}),
};
const url = entrypoint + "/alluserpls";
fetch(url, config)
.then(res => res.json())
.then(res => {
if (res.error) {
alert(res.error);
} else {
alert(`ajouté avec l'ID ${res}!`);
}
}).catch(e => {
console.error(e);
}).finally(() => this.setState({ redirect: true }));
}
render() {
return (
<div>
<form onSubmit={this.handleSubmit}>
<button type="submit">Add</button>
</form>
<CardText>{this.props.total} € </CardText>
</div>
);
}
}
const mapStateToProps = (state) => {
return {
total: state.addedItems.reduce((acc, item) => { return acc + (item.quantity *
item.price) }, 0)
//addedItems: state.addedItems
}
}
export default connect(mapStateToProps)(thisPropsFortotal)
Do you have an idea of how to fix this? Neff

You are attempting to stringify {this.props.total}, which is invalid syntax.
You can pass an object explicitely defining the total property like so:
body: JSON.stringify({total: this.props.total}),
Or, simply stringify the this.props object itself:
body: JSON.stringify(this.props),

Related

TypeError: cardsData.map is not a function

I am supposed to store queries for users in the cardsData and I need to map through the data in cardsData but if I run the code on my terminal i get this error. I am a newbie and I have searched a lot of forums that suggest that cardsData is supposed to be an array but I do not know how to go forward from there. I am just following a youTube tutorial and that was exactly what was done in the tutorial.
it worked on the youTube why can’t it work for me too?
please somebody help.
[enter image description here][1]import { useContext } from 'react'
import { TinderContext } from '../context/TinderContext'
import { SiTinder } from 'react-icons/si'
import CardHeader from './CardHeader'
import CardFooter from './CardFooter'
import TinderCardItem from './TinderCardItem'
const style = {
wrapper: `h-[45rem] w-[27rem] flex flex-col rounded-lg overflow-hidden`,
cardMain: `w-full flex-1 relative flex flex-col justify-center items-center bg-gray-500`,
noMoreWrapper: `flex flex-col justify-center items-center absolute`,
tinderLogo: `text-5xl text-red-500 mb-4`,
noMoreText: `text-xl text-white`,
swipesContainer: `w-full h-full overflow-hidden`,
}
const Card = () => {
const { cardsData } = useContext(TinderContext)
return (
<div className={style.wrapper}>
<CardHeader />
<div className={style.cardMain}>
<div className={style.noMoreWrapper}>
<SiTinder className={style.tinderLogo} />
<div className={style.noMoreText}>
No More Profiles in your Location...
</div>
</div>
<div className={style.swipesContainer}>
{cardsData.map((card, index) => (
<TinderCardItem card={card} key={index} />
))}
</div>
</div>
<CardFooter />
</div>
)
}
export default Card
I just edited this post and below is my TinderContext
import { useState, createContext, useEffect } from 'react'
import faker from '#faker-js/faker'
import { useMoralis } from 'react-moralis'
export const TinderContext = createContext()
export const TinderProvider = ({ children }) => {
const { authenticate, isAuthenticated, user, Moralis } = useMoralis()
const [cardsData, setCardsData] = useState([])
const [currentAccount, setCurrentAccount] = useState()
const [currentUser, setCurrentUser] = useState()
useEffect(() => {
checkWalletConnection()
if (isAuthenticated) {
requestUsersData(user.get('ethAddress'))
requestCurrentUserData(user.get('ethAddress'))
}
}, [isAuthenticated])
const checkWalletConnection = async () => {
if (isAuthenticated) {
const address = user.get('ethAddress')
setCurrentAccount(address)
requestToCreateUserProfile(address, faker.name.findName())
} else {
setCurrentAccount('')
}
}
const connectWallet = async () => {
if (!isAuthenticated) {
try {
await authenticate({
signingMessage: 'Log in using Moralis',
})
} catch (error) {
console.error(error)
}
}
}
const disconnectWallet = async () => {
await Moralis.User.logOut()
setCurrentAccount('')
}
const handleRightSwipe = async (cardData, currentUserAddress) => {
const likeData = {
likedUser: cardData.walletAddress,
currentUser: currentUserAddress,
}
try {
await fetch('/api/saveLike', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(likeData),
})
const response = await fetch('/api/checkMatches', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(likeData),
}
)
const responseData = await response.json()
const matchStatus = responseData.data.isMatch
if (matchStatus) {
console.log('match')
const mintData = {
walletAddresses: [cardData.walletAddress, currentUserAddress],
names: [cardData.name, currentUser.name],
}
await fetch('/api/mintMatchNft', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(mintData),
})
}
} catch (error) {
console.error(error)
}
}
const requestToCreateUserProfile = async (walletAddress, name) => {
try {
await fetch(`/api/createUser`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
userWalletAddress: walletAddress,
name: name,
}),
})
} catch (error) {
console.error(error)
}
}
const requestCurrentUserData = async walletAddress => {
try {
const response = await fetch(
`/api/fetchCurrentUserData?activeAccount=${walletAddress}`,
)
const data = await response.json()
setCurrentUser(data.data)
} catch (error) {
console.error(error)
}
}
const requestUsersData = async activeAccount => {
try {
const response = await fetch(
`/api/fetchUsers?activeAccount=${activeAccount}`,
)
const data = await response.json()
setCardsData(data.data)
} catch (error) {
console.error(error)
}
}
return(
<TinderContext.Provider
value={{ connectWallet,
disconnectWallet,
cardsData,
currentAccount,
currentUser,
handleRightSwipe
}}
>{children}
</TinderContext.Provider>
)
}
It's very likely your state cardsData is not being initialized correctly as an [] or its been set wrongly to a value different than an Array.
Hard to go further than this without TinderContext code

Need help to display data from external API

I fetched some data from an API, Im trying to display the data but I'm doing something wrong. Can someone help? I have attached a photos of the fetched data on the console and my code[![data api
import React, {useState, useEffect} from 'react'
import './Track.css';
export default function Track() {
const [carbon] = useState([])
useEffect( () => {
const headers = {
'Accept':'application/json'
};
fetch('https://api.carbonintensity.org.uk/intensity',
{
method: 'GET',
headers: headers
})
.then(function(res) {
return res.json();
}).then(function(body) {
console.log(body);
});
})
return (
<div>
<p>Track</p>
<div>
<p>{carbon.forecast}</p>
</div>
</div>
)
}
]1]1
Change to
import React, { useState, useEffect } from 'react'
import './Track.css';
export default function Track() {
const [carbon, setCarbon] = useState([])
useEffect(() => {
const headers = {
'Accept': 'application/json'
};
fetch('https://api.carbonintensity.org.uk/intensity',
{
method: 'GET',
headers: headers
})
.then(function (res) {
setCarbon(res.data)
}).then(function (body) {
console.log(body);
});
})
return (
<div>
<div>
{carbon.map((obj, i) => (
<li key={i}>
<ul>{obj.from}</ul>
</li>
))}
</div>
</div>
)
}
I recommend to you study https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Array/map
you forgot some little thing:
first you forgot the setCarbon in the useStae hook you will need it to pass the response from the fetch.
You forgot to set the state in the fecth.
You will need to add a condition to render only when the state (carbon) is set.
you need to add an empty dependency to useEffect
import React, { useState, useEffect } from "react";
export default function Track() {
const [carbon, setCarbon] = useState([]);
useEffect(() => {
const headers = {
Accept: "application/json"
};
fetch("https://api.carbonintensity.org.uk/intensity", {
method: "GET",
headers: headers
})
.then((res) => {
return res.json();
})
.then((body) => {
console.log(body.data);
setCarbon(body.data);
});
}, []);
return (
<div>
<p>Track</p>
{carbon.length > 0 && (
<div>
{carbon.map((c, i) => (
<p key={i}>
<div>from: {c.from} </div>
<div>to: {c.to}</div>
<div>forecast: {c.intensity.forecast}</div>
<div>actual: {c.intensity.actual}</div>
<div>index: {c.intensity.index}</div>
</p>
))}
</div>
)}
</div>
);
}
Here you go,
Remember, state is like a place to store data for your component.
When you use fetch, you are getting data and now you need to save it to your state.
If you use state inside of your JSX, you can get the information to display.
Check out the console log, to look at the data structure that is returned from the fetch. This is what is set to the state "data". It can be called whatever you want. You can iterate through it, and dynamically display the data in JSX if you wanted, but I just hardcoded it for you so it's easier to understand.
const [data, setData] = useState([]);
useEffect(() => {
fetch("https://api.carbonintensity.org.uk/intensity", {
method: "GET",
headers: {
"Content-Type": "application/json"
}
})
.then((res) => res.json())
.then((data) => setData(data))
.catch((e) => console.error(e));
}, []);
console.log("data:", data);
return (
<div>
<p>Track</p>
<div>
<p>From: {data.data["0"].from}</p>
<p>To: {data.data["0"].to}</p>
<div>Intensity:</div>
<p>forecast: {data.data["0"].intensity.forecast}</p>
<p>forecast: {data.data["0"].intensity.actual}</p>
<p>forecast: {data.data["0"].intensity.index}</p>
</div>
</div>
);

How can I POST data using API from REACTJS?

This is my react code here I want to POST Data using postPoll API and update polls state but I am not understand how can do that.
please help..! please help..!please help..!please help..!please help..!please help..!please help..! at line number 33, 34 ( handalchange )
import React, { useState, useEffect } from "react";
import Poll from "react-polls";
import "../../styles.css";
import { isAutheticated } from "../../auth/helper/index";
import { getPolls, postPoll } from "../helper/coreapicalls";
import axios from "axios";
import { API } from "../../backend";
const MainPoll = () => {
const userId = isAutheticated() && isAutheticated().user._id;
const [polls, setPoll] = useState([]);
const [error, seterror] = useState(false);
useEffect(() => {
loadPoll();
}, []);
const loadPoll = () => {
getPolls().then((data) => {
if (data.error) {
seterror(data.error);
} else {
setPoll(data);
console.log(data);
}
});
};
// Handling user vote
// Increments the votes count of answer when the user votes
const handalchange = async (pollId, userId, answer) => {
console.log(pollId); // getting
console.log(userId); // getting
console.log(answer); // getting
await axios.post(`${API}/vote/${pollId}`, userId, answer);
// postPoll(pollId, { userId, vote }).then(() => {
// loadPoll();
// });
};
return (
<div className="">
<div className="container my-5">
<h1 className="blog_heading my-3">Poll's of the Day</h1>
<div className="row">
{polls.reverse().map((poll, index) => (
<div className="col-lg-4 col-12 poll_border" key={index}>
<Poll
noStorage
question={poll.question}
answers={Object.keys(poll.options).map((key) => {
return {
option: key,
votes: poll.options[key].length,
};
})}
onVote={
(answer) =>
handalchange(poll._id, userId, answer, console.log(answer)) // getting vote
}
className="mb-2"
/>
</div>
))}
</div>
</div>
</div>
);
};
export default MainPoll;
this is my frontend-
POSTMAN - request = >
and here is my backend API -
// post
export const postPoll = (pollId, post) => {
return fetch(`${API}/vote/${pollId}`, {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
body: JSON.stringify(post),
})
.then((response) => {
return response.json();
})
.catch((err) => console.log(err));
};
It depends on what object does onVote event from Poll component pass. But if it's vote object, that's required in postPoll method as second arguement, than:
function in onVote event should pass poll.id from this component and vote object from Vote component onVote event itself:
onVote={(vote) => handalchange(poll.id, vote)}
handalchange should fire postPoll api method with these arguements and load updated poll data on success:
const handalchange = (pollId, vote) => {
postPoll(pollId, vote).then(() => {
loadPoll();
});
}

Reach router refresh page

Setup:
I have a form that send data to an action creator, which in turn submits to an API and gets the result. What I want is when the form submits successfully, to refresh the form with blank inputs.
This is how the component looks like
import React, { Component } from "react";
import { bindActionCreators } from "redux";
import { connect } from "react-redux";
import { addNewProduct } from "../../redux/actions";
class Admin extends Component {
state = {
ProductName: ""
};
onChange = e => {
e.preventDefault()
this.setState({
[e.target.name]: e.target.value
})
}
handleProductSubmit = (event) => {
event.preventDefault();
this.props.addNewProduct(
this.state.ProductName,
);
}
render() {
return (
<div>
{/* Form ends */}
<form onSubmit={this.handleProductSubmit} autoComplete="off">
<input
type="text"
value={this.state.ProductName}
name="ProductName"
onChange={this.onChange}
/>
<button type="submit" className="btn btn-dark">
Upload Product
</button>
</form>
{/* Form Ends */}
</div>
);
}
}
const mapDispatchToProps = (dispatch) => {
return bindActionCreators({ addNewProduct, createNewLogin }, dispatch);
};
export default connect(null, mapDispatchToProps)(Admin);
This is the result of the console.log(this.props)
location: Object { pathname: "/Home/admin", href: "http://localhost:3000/Home/admin", origin: "http://localhost:3000", … }
navigate: navigate(to, options)
​​
length: 2
​​
name: "navigate"
​​
prototype: Object { … }
​​
<prototype>: ()
This is how the actionCreator looks like
export const addNewProduct = (ProductName, ProductCategory, ProductImg) => (dispatch) => {
const productData = new FormData();
productData.append("ProductName", ProductName)
axios.post("http://localhost:4500/products/", productData,
{
headers: {
"Content-Type": "multipart/form-data",
"Authorization": localStorage.getItem("Authorization")
}
})
.then(res => {
console.log(res.data)
setTimeout(() => {
console.log("doing the timeout")
navigate("/Home/admin")}, 1500);
})
.catch(err =>
console.log(`The error we're getting from the backend--->${err}`))
};
Current behavior
When I submit the form and the API return 201, the page does not refresh and the inputs do not go blank
Expected behavior:
When I get a 201 from the API, the page should refresh and the inputs should be blank.
Please help me how to achieve this.
Using navigate to move the same url or page won't remount the page and reset your field values.
Its better is you actually return a promise from your action creator and reset the state yourself
export const addNewProduct = (ProductName, ProductCategory, ProductImg) => (dispatch) => {
const productData = new FormData();
productData.append("ProductName", ProductName)
return axios.post("http://localhost:4500/products/", productData,
{
headers: {
"Content-Type": "multipart/form-data",
"Authorization": localStorage.getItem("Authorization")
}
})
.then(res => {
console.log(res.data)
})
.catch(err =>
console.log(`The error we're getting from the backend--->${err}`))
};
In the component
handleProductSubmit = (event) => {
event.preventDefault();
this.props.addNewProduct(
this.state.ProductName,
).then(() => {
this.setState({ProductName: ""})
});
}

How to use the response in fetch request React Native

I am new in react native world and (JS).
I want to send phone number and password to the server to login. I can send data and receive response, however, I don't how I should handle response. I have a function called _response_recognizer. But it is not working. Even setStat. All of the tutorials only say how to connect to server and how fetch data from it. What is the best approach to use response in my login form. If it's status is 200 I want to navigate another screen, else I want to toast a message.
import React, {Component} from 'react';
import {
Platform,
StyleSheet,
Text,
View,
TextInput, Button
} from 'react-native';
export default class LoginForm extends Component<{}> {
constructor(props) {
super(props);
this._onLogInPressed = this._onLogInPressed.bind(this);
this._response_recognizer = this._response_recognizer.bind(this);
this.state = {
phone_number: '',
password: '',
data: {}
};
}
_response_recognizer(data: string ){
}
_onLogInPressed = () => {
var data = {
'phone_number': this.state.phone_number,
'password': this.state.password
}
fetch("http://192.168.1.12:5000/login", {
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(data)
}).then(function(response){
return response.json();
}).then(function(data){
console.log(data)
this._response_recognizer(data)
}) .catch((error) => {
console.log("Error" + error);
});
};
render() {
return (
<View style={styles.flow}>
<Text style={styles.text}>phone number:</Text>
<TextInput keyboardType='numeric'
style={styles.input}
ref="phone_number"
onChangeText={(phone_number) => this.setState({phone_number})}
maxLengt={11}
value={this.state.phone_number}
/>
<Text style={styles.text}>password:</Text>
<TextInput style={styles.input} secureTextEntry={true} ref="password"
onChangeText={(password) => this.setState({password})}
value={this.state.password}/>
<Button style={styles.button} onPress={this._onLogInPressed} title='login'/>
</View>
);
}
}
Two things.
Your _response_recognizer function is requesting data: string but you are returning an json object:
.then(function(response){
return response.json();
}).then(function(data){
console.log(data)
this._response_recognizer(data)
})
Change that to data: object.
Secondly, you are using function declarations (function(){}) in your .then's. Without directly binding this, you lose the scope your Class functions. Change them to an arrow function (() => {}) to fix the scope issue:
.then((response) => response.json())
.then((data) => {
console.log(data)
this._response_recognizer(data)
})
You can also opt to remove one of the .then operations:
.then((response) => {
console.log(response.json())
this._response_recognizer(response.json())
})
✌🏾
check this ...
i hope this code helps you
export default class LoginForm extends Component<{}> {
state = {
data:[],
}
_onLogInPressed = () => {
fetch('http://192.168.1.12:5000/login',{
method:'POST',
headers:{
'Accept':'application/json',
'Content-Type':'application/json',
},
body:JSON.stringify({
'phone_number': this.state.phone_number,
'password': this.state.password
})
})
.then((response) => response.json())
.then((res) =>{
if(res.success === true){
alert(res.response);
let datadata = res.data;
this.setState({data:datadata})
} else {
alert(res.response);
}
})
.done();
};
//// Render function
////Rander function
}

Categories

Resources