'Setting state with values inside an object
Im basically trying to set the state with the City value but when I set thee state and console log the state its always empty. Im even console logging along the way.
sample city object from first console.log: {_id: '625a495ae4bea1099502f824', City: 'Dakhla Oasis' Country: 'Egypt' }
import React from "react";
import { useState } from "react";
export default function Cities() {
const [singlecity, setSingleCity] = useState('');
function GetSingleCity() {
console.log(city)
setSingleCity(city.City);
console.log(singlecity);
}
Solution 1:[1]
setState function in react is asynchronous, so if you console.log right after the set state, you will not see the updated value immediately. However if yo try to render the state, you will see the rendered html will be updated. If you want to console.log the latest value of singleCity, you could either move the console.log outside GetSingleCity, so console.log will run on every re-render, or put console.log inside a useEffect:
useEffect(() => {console.log(singleCity)}, [singleCity])
useEffect will run the callback every time the state singleCity has changed, so you will see the updated value
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | wyfy |
