Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to use useState inside inner function scope in react.js hooks

I am completely new to react.js.

I am fetching async data from my server that uses express.js. After I get that data I want to set my house parameters when I open that page for the first time.

const Houses = () => {
const [house, setHouse] = useState({});

...

useEffect(() => {
    const fetchData = () => {
        fetch('http://localhost:9000/houses')
            .then(res => res.text())
            .then(res => {
                if (res) {
                    let houseData = JSON.parse(res);
                    console.log(houseData); // server res prints correctly - prints: { name: 'sweet house', address: 'fukuoka hakata' }
                    setHouse({...house, houseData});
                    console.log(house); // doesnt change after sethouse - prints : {}
                }
            });
    }

    fetchData();
}, []);

...

}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Im getting the data from my server without any problem.
The problem is that the house parameters dont get updated. I know its a different scope, what I need to know is how I do it in this case. Thanks

>Solution :

You cannot access the houseData immediately after setting it, setHouse will be batched.

See more of states: https://reactjs.org/docs/state-and-lifecycle.html

Try changing

setHouse({...house, houseData})

to

setHouse(houseData)

since houseData is an Object.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading