简体   繁体   中英

How to access the updated state after setState method with react hooks?

On button click I want to set the state to selectedMealPlan , store the updated state to the localStorage and route to another component.

  const [selectedMealPlan, setSelectedMealPlan] = useContext(
    selectedMealPlanContext
  );
  const AddItem = (e: any) => {
    setSelectedMealPlan((prev: any) => ({
      ...prev,
      nutrients: {
        newValue: "newValue",
      },
    }));
    localStorage.setItem("mealplan", JSON.stringify(selectedMealPlan))
    history.push("/home");
  };

The problem is that setState() is asynchronous and I can only store the old state to localStorage, is there a way that I could access the most recent state?

I'd use useEffect to watch for changes to selectedMealPlan , and when detected, call setItem :

const AddItem = (e: any) => {
    setSelectedMealPlan((prev: any) => ({
        ...prev,
        nutrients: {
            newValue: "newValue",
        },
    }));
};
useEffect(() => {
    localStorage.setItem("mealplan", JSON.stringify(selectedMealPlan))
    history.push("/home");
}, [selectedMealPlan]);

You could also save the new state object in a variable inside the setSelectedMealPlan callback, and both call setItem with it and return it for the new state, but that'd be impure and weird.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM