Reputation: 749
How do I update the state data immediately when I use Axios with async and await? It seems not updating the state data immediately. Many thanks in advance and greatly appreciated. Here is the code sample:
const[dbdata,setDBData] = useState([])
useEffect(async() => {
const response = await Axios.get('http://localhost:5000/api/posts/allpost', {withCredentials:true})
setDBData(response.data)
}, [])
const GetPost = async(id) =>{
const response = await Axios.put('http://localhost:5000/api/posts/getPost',{postId:id}, {withCredentials:true})
const getData = dbdata.map(item => {
if(item._id==response._id){
return response
}
else{
return item
}
})
console.log(getData)
setDBData(getData)
}
Upvotes: 0
Views: 275
Reputation: 13078
useEffect(async () => ...) are not supported, but you can call an async function inside an effect.
Try:
useEffect(() => {
const GetPost = async(id) =>{
const response = await Axios.put('http://localhost:5000/api/posts/getPost',{postId:id}, {withCredentials:true});
const getData = dbdata.map(item => {
if(item._id==response._id){
return response;
}
else{
return item;
}
})
console.log(getData);
setDBData(getData);
}
GetPost();
}, [])
EDIT:
OR:
useEffect(() => {
GetPost();
}, []);
const GetPost = async(id) =>{
const response = await Axios.put('http://localhost:5000/api/posts/getPost',{postId:id}, {withCredentials:true});
const getData = dbdata.map(item => {
if(item._id==response._id){
return response;
}
else{
return item;
}
})
console.log(getData);
setDBData(getData);
}
Upvotes: 1