0

I'm building a react app. I tried to make an axios call to the database, and it should return an array of objects with the image id, and then I make another axios call to get all the image urls and add them into the original array. The data object returned from getSrc is updated with the correct url property, but when I set the data object to sessionStorage, it has no url property. I really don't understand why it behaves like this, pls help thank you so much.



  const [items, setItems] = useState([]);

  const getSrc = (datas) => {
    return axios.all(
      datas.map((data) => {
        axios
          .get(
            `https://database/${data.imageID}`,
            {}
          )
          .then((res) => {
            if (res.status != 200 || !res.data) {
              throw res;
            } else {
              let src = "data:image/jpeg;base64,";
              src += res.data;
              data.url = src;
         
            }
          })
          .catch((err) => {
            console.log(err);
          });
      })
    );
  };
  useEffect(() => {
    axios
      .get("https://server/getPage", {})
      .then((res) => {
        if (res.status != 200 || !res.data) {
          throw res;
        } else {
          const data = res.data;
          getSrc(data).then(() => {
            setItems(data);
            console.log(data);//updated
            sessionStorage.setItem("items", JSON.stringify(data));
            console.log(JSON.parse(sessionStorage.getItem("items")));// original object
          });
        }
      })
      .catch((err) => {
        console.log(err);
      });
  }, []);


Output:This is the output of the two console.log, the first one is the updated object, the second one is the one from sessionStorage

zzen
  • 1
  • 1
  • Does `console.log(JSON.parse(JSON.stringify(data)));` print updates object? – Konrad Nov 13 '22 at 08:23
  • By the way your URL is bad, it claims to be base64 but it's raw and not even URL-encoded – CherryDT Nov 13 '22 at 08:29
  • You have a missing `return` before `axios .get( https` – Konrad Nov 13 '22 at 08:31
  • 1
    The problem is that your `getSrc` does not correctly await the inner `axios.get` calls because you don't return their promises from the `map` callback. Therefore the function returns immediately and the requests continue in the background. The URL field gets set after the rest of your code already ran. The reason why you see it in the console anyway is because the browser will load this information only in the moment you click the expand arrow, which will be after it was already changed, even though it was not yet changed when the `console.log` ran. – CherryDT Nov 13 '22 at 08:31

0 Answers0