简体   繁体   中英

Infinite loop + wrong output when trying to get key/value pair from localStorage in React.useEffect

I'm trying to GET queries from my API with all key=fld_id/value=true pairs in local storage "Selected Fields".

This is how "Selected Fields" appears in the localStorage (they are stored form checkbox form submission): https://i.imgur.com/nbmC80Z.png

It keeps running an infinite loop in the backend that eventually crashes my browser and inserts wrong fld_id (which is the key in the localStorage): https://i.imgur.com/tzueONR.png

const [monitoringData, setMonitoringData] = React.useState(null);

const selected = localStorage.getItem("Selected Fields");

  Object.keys(selected).forEach((fld_id) => {
    axios
      .get("/api/parsed-logs-list/?fld_id=" + fld_id)
      .then((response) => {
        setMonitoringData([...monitoringData, fld_id.response.data]);
      })
      .catch((error) => {
        setMonitoringData({ status: "error" });
      });
  });

Can someone help me resolve this issue please?

Edit: Solution provided in a later comment below to avoid confusions.

Firstly, you must wrap your side effect in useEffect hook (otherwise after each rerender you make request and update state, that cause to infinite loop). Secondly, type of value you receive from localStorage is string not object , you must parse with JSON.parse(selected) before calling Object.keys

With the help of @Mike and @AlaaEddineCherif, it now works as intended so I'm posting the solution in a different post in case it will be of help to someone else one day.

  React.useEffect(() => {
    const selected = JSON.parse(localStorage.getItem("selected_fld_id"));

    Object.keys(selected).forEach((fld_id) => {
      axios
        .get("/api/parsed-logs-list/?fld_id=" + fld_id)
        .then((response) => {
          setMonitoringData((prev) => [...prev, response.data]);
          // console.log(response.data);
        })
        .catch((error) => {
          setMonitoringData({ status: "error" });
        });
    });
  }, []);

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