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

Time:01-23

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();
    }, []);

    ...
}

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

CodePudding user response:

You cannot access the house state immediately after setting it, setHouse may be batched.

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

You are trying to do

let houseData = JSON.parse(res);
 // houseData =  { name: 'sweet house', address: 'fukuoka hakata' }
setHouse({ ...house, houseData: houseData });

instead of setHouse(houseData). Since houseData is an Object, you can directly set it.

Replace

setHouse({...house, houseData})

with

setHouse(houseData)
  •  Tags:  
  • Related