0

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);
  }
  • Does this answer your question? [The useState set method is not reflecting a change immediately](https://stackoverflow.com/questions/54069253/the-usestate-set-method-is-not-reflecting-a-change-immediately) – JBallin Apr 19 '22 at 05:07

1 Answers1

0

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

wyfy
  • 361
  • 1
  • 3
  • 8