recently I encountered a problem, the code is as below:
const [data, setData] = useState("");
useEffect(()=>{
axios.get("http://localhost:4000/getData")
.then(res => {
setData(res.data); //res = {data: "xxx"}
}).catch(err => console.log(err);
console.log(data);
axios.post("http://localhost:4000/postData",{data: data}).then(res=>console.log(res)).catch(err => console.log(err);
},[]);
- If I console.log the res in the get request, I can see the res and it is something I want.
- But when I console.log the data updated by useState in the next line, it is still the initial state, but not the updated one.
- In the postData route of server, the console.log of req.body.data is still the initial state.
So are there any ways to get the response, update state, and then send the post request with the updated state inside the useEffect hook every time?