Search code examples
reactjsaxiosreact-hooksfetch

React Fetch with State Value


I've two different API URL. I can get current user's ID with /api/current_user and save into "currentuser" state. I want to fetch all currentuser's from MySQL. My API URL works. But i couldn't fetch with currentuser state variable.

This link returns currentuser's ID. It works.

  useEffect(()=>{
    
    fetch('http://localhost:8000/api/current_user/', {
      headers: {
        Authorization: `JWT ${localStorage.getItem('token')}`
      }
    })
      .then(res => res.json())
      .then(json => {
        setCurrentuser(json.id);
      });
  
  
},[]) 

Then i want to use that ID with currentuser state.

 Axios.request({
      method: 'POST',  
      url: 'http://localhost:3001/api/post',
      data: {
        curus: `${currentuser}`     // I'm trying to use currentuser state on here.
      },
     })

    .then(response => {
      return response.data;
  })
    .then(data => {
      let tmpArray2 = []
      const tmpArray = []
bla bla bla ...

Finally request payload returns curus: ""

So it have a null value. I can use this state value inside return function.

Also that's my node server's index.js:

app.post('/api/post', (req, res) => {
    const currentt = req.body.curus
    const sqlSelect = "SELECT * FROM messagestable WHERE sender='" + currentt + "' OR recipient ='" + currentt + "' ";
    db.query(sqlSelect, (err, result) => {
        res.send(result);
        console.log(currentt)
    });

})

I want to fetch all messages from MySQL but just for currentuser. Not all users messages. May you help me? Thanks a lot!


Solution

  • You can't call fetch and Axios.request in succession because setCurrentuser is async and when you use currentuser in Axios.request you don't know if currentuser has the very last value.

    Much better split fetch and Axios.request into 2 useEffect in this way:

    useEffect(()=>{  //<-- this will be fired on component's loading
        
        fetch('http://localhost:8000/api/current_user/', {
          headers: {
            Authorization: `JWT ${localStorage.getItem('token')}`
          }
        })
          .then(res => res.json())
          .then(json => {
            setCurrentuser(json.id);
          });
      
      
    },[]) 
    
    useEffect(() => { //<-- this one will be fired every time you change currentuser and will contains the very last value of currentuser
      Axios.request({
      method: 'POST',  
      url: 'http://localhost:3001/api/post',
      data: {
        curus: `${currentuser}`
      },
     })
    
    .then(response => {
      return response.data;
    })
    .then(data => {
      let tmpArray2 = []
      const tmpArray = []
      bla bla bla ...
    
    }, [currentuser])