0

This problem only occurs when I run my React/Express app in development mode through a Webpack proxy. I am essentially looking to post some data to and retrieve some data from my Express server at /post. The request goes through successfully with a 200 response.

It has no problem going through the setState function, but if I print the state after it is still null despite what I set it to being a valid string. As such the data I am looking to display on screen when it is called is never displayed. As can be seen in the photo attached the data is all valid but the state ends up being set to 0.

Everything functions properly if I build it before running and do not get the response through a proxy.

Here is the entire repo and the relevant component:

// First of all, I use state with a object as follows.
let [returnQuery, setReturnQuery] = React.useState({
    price: null,
    connections: null,
    leaves: null,
    returns: null,
    link: null
})

// Following I fetch from my express server.
async function postData() {
    const response = await fetch('/search', {
        method: "POST",
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(props.searchState)
    })
    return response.json();
}

// After this I set my state as this return value
postData().then((data) => {
    console.log(`data returned ${data.link}`)
    setReturnQuery({
            price: data.price,
            connections: data.connections,
            leaves: data.leaves,
            returns: data.returns,
            link: data.link
    })
    setTimeout(() => console.log(returnQuery), 5000)
})

What my console returns

jonrsharpe
  • 107,083
  • 22
  • 201
  • 376
  • Calling `setReturnQuery` will not (and can not) change the value in the local variable `returnQuery`. The purpose of `setReturnQuery` is to tell react to render the component again. When that new render happens, a new local variable will be created with the new value, but code from the previous render has no access to it. If you'd like to verify that this rerender is happening, put the console.log in the body of the component (say, right after the `let [returnQuery, setReturnQuery] /*etc*/` line) – Nicholas Tower Feb 03 '22 at 14:07

0 Answers0