0
votes

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);
},[]);
  1. If I console.log the res in the get request, I can see the res and it is something I want.
  2. 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.
  3. 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?

1
Ok so you'll need to probably do some tutorials on sync vs. async code in Javascript, as well as Promise syntax and async/await syntax. You're treating the axios calls and their callbacks as if they're synchronous, it doesn't work like that. Someone could rewrite it for you so that it's correct, but you'll just face the problem again if you don't understand asynchronous code in Javascript and the correct syntaxes for these thingsJayce444

1 Answers

0
votes

So what you are having there is you are setting the wrong data, you are using setData(data) instead it should be setData(res.data)

const [data, setData] = useState("");

useEffect(()=>{
  axios.get("http://localhost:4000/getData").then(res => setData(res.data)).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);
},[]);

But if you want to use "data" this is how you can go about it:

const [data, setData] = useState("");

useEffect(()=>{
  
  async function loadData(){
   
    const {data} = await axios.get(url);
    
    //Now in this case you can use 
    setData(data)

  }
  
  loadData();

  axios.post("http://localhost:4000/postData",{data: data}).then(res=>console.log(res)).catch(err => console.log(err);
},[]);