0
const [calculatedData, setCalculatedData] =useState(""); 

const calculateOrder = async() =>{

    try{
        
        const dataBody = `json=${encodeURIComponent(JSON.stringify(testInfo))}`;

        const responseObj = await fetch('API', {

            method: 'POST',
            headers:{
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: dataBody
        });

        const res = await responseObj.json();
        setCalculatedData(res);
        console.log(res); // Perfectly display data

    } catch(e){

        console.log(e)
    }
    
}

I am trying to save the response data to 'calculatedData', but I only get an empty string. Can anyone provide me any suggestion?

console.log(calculatedData) //Empty string
Frances
  • 23
  • 3

1 Answers1

0

useState (or setCalculatedData) is asynchronous(just like setState) and changes would not be reflected immediately. As the data is not stored yet in the calculatedData when you console it, you would only receive the empty string. Please follow this answer for more information

alisasani
  • 2,808
  • 1
  • 7
  • 15