How to set object hook properly in React?

Viewed 39

I have these states:

const [maintenanceTypeId, setMaintenanceTypeId] = useState(null);
const [maintenanceId, setMaintenanceId] = useState(null);

const [addedId, setAddedId] = useState({
    mainId : null,
    mainTypeId : null,
  });

I set states in these functions: //setMaintenanceTypeId //setAddedId

const addNewMainTypesList = async () => {
    try {
      const { data } = await axios.post(`${serverBaseUrl}/insertRowtoMainTypes`, {
        description: newMaintenanceList.description,
        title: newMaintenanceList.title
      });
      setMaintenanceTypeId(data[0]?.id);
      console.log("MaintenanceTypeId", maintenanceTypeId);
      //console.log("inserted type id",data[0]?.id);
      setAddedId({...addedId, mainTypeId : maintenanceTypeId});
    } catch (err) {
      throw err;
    }

    const maintenanceList = await getMainTypes();
    // console.log("main list", maintenanceList);
    setMaintenanceList(maintenanceList);
  };

//setMaintenanceId //setAddedId

const addNewMainTypes = async () => {
    try {
      const { data } = await axios.post(`${serverBaseUrl}/insertRowtoMain`, {
        nodeid: newMaintenance.nodeid,
        maintenancetype: newMaintenance.maintenancetype,
        personnel: newMaintenance.personnel,
        process: newMaintenance.process,
        date: newMaintenance.date,
      });
      setMaintenanceId(data[0]?.id);
      console.log("MaintenanceId", maintenanceId);
      setAddedId({...addedId, mainId : maintenanceId});
      //console.log("inserted main id",data[0]?.id);
      
    } catch (err) {
      throw err;
    }

I am console logging the addedId state in a submitHandler.

 const submitHandler = (e) => {
    e.preventDefault();

    addNewMainTypesList();
    getMain();
    getMainTypes();
    addNewMainTypes();


    console.log("addedId",addedId);

  }

Here is the console. As you can see, I can not get the maintenanceTypeId. How can I fix this?

console

1 Answers

setState is an asynchronous function. In other words, it won't directly update a given state.

In your case setMaintenanceTypeId is not directly updating maintenanceTypeId.

In order, to make it update directly, use inside of it an anonymous function, like this:

setMaintenanceTypeId(mTypeId => data[0]?.id);

It would be also better if you do the same for setAddedId (though not mandatory):

setAddedId(addedId => {...addedId, mainTypeId : maintenanceTypeId});

Let me know if this still doesn't work.

Related