skip to Main Content

I am having a search button in my code which takes gatewayId as input from user. Displaydata function invokes when user click on search button.Then, it make visibility of another div true through setToggle state and invoke loadDetails function. It setdetails equals to the fetch details through axios.

  const displaydata = (e) => {
    setToggle(true);
    loadDetails();
    console.log(details);
  };
  

  const loadDetails = async()=>{
    await axios.get(`http://localhost:8282/changeShipmentDetails/${gatewayId}`)
    .then((response)=>{
        setToggle(true);
        setdetails(response.data);
    })
    .catch(error=>{
        setToggle(false);
        setMsg(error.response.data);
      
    });
  };

But on clicking first time, it provide null then on second click it produce result in console.
How to fix it?

2

Answers


  1. React batches state updates, and when you perform a setState, it is not reflected in the code on the console log on the next line. It has batched the state update, and on first click it is fetching the current state still which is null.

    You can do something along the lines of

    setDetails(() => {
        console.log(response.data)
        return response.data
    })
    

    which should show you what you expect, also remove the setToggle in the displaydata function as it is called in the loadDetails function

    Login or Signup to reply.
  2. It’s because you don’t wait until the results are fetched. Also, when you use console.log() inside the displayData function, it always displays the initial data. Not the updated data. To console.log the updated data, you need to log it outside:

    const displaydata = (e) => {
      setToggle(true);
      await loadDetails();
      console.log('data fetched') // With the await in the line above, this line waits until the data is fetched
    };
    
    console.log(details); // This will console log data once it's fetched.
      
    
    const loadDetails = async()=>{
      await axios.get(`http://localhost:8282/changeShipmentDetails/${gatewayId}`)
        .then((response)=>{
          setToggle(true);
          setdetails(response.data);
      })
      .catch(error=>{
          setToggle(false);
          setMsg(error.response.data);    
      });
      return true
    };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search