I have written an axios request in react-native useEffect.The request is succesfull in backend and returning a the right response in terminal.But the useEffect hook is not working according to it.It is still returning product as undefined and not changing the state. If it all works well the product would contain the product variable. It only works when I save it again and then it shows the product. Am I missing something here? Thanks in Advance !!
const [product, setProduct] = useState();
useEffect( () => {
getproductinfo()
if (props.editMode) {
AsyncStorage.getItem("jwt")
.then((res) => {
setToken(res);
})
.catch((error) => console.log(error));
}
console.log(product, "this is product");
},
[],
)
this is my function
const getproductinfo = async () => {
await axios
.get(`${baseURL}products/get/product/${props.product}`)
.then((res)=> {setProduct(res.data)
})
.catch((error)=> {
console.log(error);
console.log("this is order card product card error ")
});
}
getproductinfo
is an async function and you don't use await in the useEffect hook so the code continues to run while the axios request is not yet resolved. However you can't use an async function as useEffect so I suggest the following approach
useEffect( () => {
const asyncFunction = async() {
await getproductinfo();
console.log(product, "this is product");
}
asyncFunction();
// Rest of your code....
},
[],
)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.