简体   繁体   中英

Persist localStorage with useContext not working

I've been struggling with React Context value disappears when refresh my nested page. So i tried to use localsStorage. Why is it still not working tho. I have tried to store data in my app component and pass it to <InfoDetails> , it works perfectly fine, but when i refresh the page, the data is gone.

function InfoContextProvider(props) {
  const { food } = useHttp("food");
  const { location } = useHttp("location");

  const info = {
    Food: food,
    Location: location,
  };

  useEffect(() => {
    localStorage.setItem("info", JSON.stringify(info));
  }, [info]);

  return (
    <InfoContext.Provider value={{ info }}>
      {props.children}
    </InfoContext.Provider>
  );
}

export { InfoContextProvider, InfoContext };

my nested page:id/:productname/



const InfoDetails = (props) => {
  const { id, productname } = useParams();
  const { info } = useContext(InfoContext);

  const item = JSON.parse(localStorage.getItem("info"));


  const data = item[id].find((name) => name.name === productname);



  return (
    <>
      <div className={classes.container}>
          <img src={data.image} alt="" />
     </div>
    </>
  );
};

export default InfoDetails;




Looks like during initial render, the info object has undefined value.

That's why it has no value when reloading the page.

function InfoContextProvider(props) {
  const { food } = useHttp("food");
  const { location } = useHttp("location");

  const info = {
    Food: food,
    Location: location,
  };

  useEffect(() => {
     if(info.Food && info.Location) {
       localStorage.setItem("info", JSON.stringify(info));
     }
  }, [info]);

  return (
    <InfoContext.Provider value={{ info }}>
      {props.children}
    </InfoContext.Provider>
  );
}

export { InfoContextProvider, InfoContext };

Do check the info value before setting it into the localStorage .

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