Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

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

    ...
}

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

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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)
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!