2

I've a problem with React, I want to update a state variable with an object, but it doesn't update anything. Code:

async function getServers() {

        console.log("ready")

        const response = await fetch('http://localhost:3000/server/servers').then(res => res.json())

        setServers(response);
        console.log(response)

        console.log("servers object updated: " + JSON.stringify(servers));
    }

    useEffect(() => {
        getServers();
        import('bootstrap/dist/js/bootstrap');
        WebFont.load({
            google: {
                families: [ 'Karla:600', 'sans-serif' ]
            }
        });
    }, []);

Console:

console output

Someone can tell me why it doesn't update?
Thanks in advance and sorry for bad english!

BlackdestinyXX
  • 331
  • 3
  • 17
  • 1
    Does this answer your question? [React setState not Updating Immediately](https://stackoverflow.com/questions/38558200/react-setstate-not-updating-immediately) – Brendan Bond Dec 12 '21 at 18:51
  • you are calling getServers() without await before it – HDM91 Dec 12 '21 at 18:52

1 Answers1

0

This may work for you const response = await fetch('http://localhost:3000/server/servers').then(res => setServers(res.json()))

samar
  • 66
  • 3