-1

I have a method to save employee. Here I want to set the employee state with the returned saved object. It is updating the state value but not showing next line log after setEmployee(). But it is showing updated value on useEffect() on employee change. So why it is not showning after setting the value on next line although I have used await.

My code is below.

Initial state, an empty object:

const [employee, setEmployee] = useState({});

Use effect on employee:

useEffect(() => {
    console.log(">>>> inEmpolyeeUseEffect: " + employee);
}, [employee]);

Add employee method:

const addEmployee = async (empObj) => {
    try {
        const response = await axios.post(`http://localhost:9000/employee/save`, { ...empObj });
        const data = response.data;
        await setEmployee(JSON.stringify(data));
        console.log("EmployeeDataAfterSave: " + employee);  // log empty object here like {}
        
        ...
    } catch (error) {
        console.log(error +" :: " + JSON.stringify(error));
    }
}
halfer
  • 19,824
  • 17
  • 99
  • 186
Sumon Bappi
  • 1,937
  • 8
  • 38
  • 82
  • 1
    `setState` is an `async` operation, you can't read the updated value right after setting it. Thats why `useEffect` is provided which executes when the value has changed in the background. – Shaharyar Sep 09 '21 at 07:39
  • See https://stackoverflow.com/a/61842546/2805121 – Nsevens Sep 09 '21 at 07:41
  • 1
    Two things you need to know about state updates in React: 1. State is constant within a particular render of a component; component can't see the updated state _until_ it re-renders. 2. State updates are asynchronous. – Yousaf Sep 09 '21 at 07:44

1 Answers1

0

Another option besides viewing the changes to the state in the useEffect, is to use an arrow function inside the setState method to update the value, see this

Using the arrow function should allow you to immediately see the changes to the state in the console log

Nir
  • 106
  • 1
  • 7