-1

I get a data from a photos db API, and I want to create a button , after click then can save this photo to localstorage, but I try many ways still can not success come up with useState, after I refresh page, the data in localstorage would be cleared, I only can use normal way , like no useState to make it success. I want to know how could I save into localstorage by useState

import React, { useEffect, useState } from "react";

const Pics = ({ data }) => {
  //----------------useState way---------------------------
  //------not work----------------------------------------
  // useEffect(()=>{
  // localStorage.setItem("F",JSON.stringify(lovepic))
  // },[lovepic])

 // let [lovepic, setlovepic] = useState([]);
 //----------------useState way---------------------------




//----this code can save into localstorage but not use useState------
  const savelove = () => {
    let mylist = localStorage.getItem("k");
    if (mylist == null) {
      localStorage.setItem("k", JSON.stringify([data]));
    } else {
      let listarr = JSON.parse(mylist);
      listarr.push(data);
      localStorage.setItem("k", JSON.stringify(listarr));
    }
    


    //--------------------------useState----------------
    ////------not work----------------------------------------
    // setlovepic([...lovepic,data])
    //localStorage.setItem("F",JSON.stringify([...lovepic,data]))
    //--------------------------useState----------------
  };
  return (
    <div className="pic">
      <p>{data.photographer}</p>
      <div className="imgcontainer">
        <img src={data.src.large} alt="" />
      </div>
      <p>
        download:
        <a tager="_blank" href={data.src.large}>
          clik here
        </a>
        <button onClick={savelove}>favrite</button>
      </p>
    </div>
  );
};
export default Pics;
coolboy
  • 1
  • 1
  • See this [related Q&A](https://stackoverflow.com/a/73940902/633183) for a `useLocalStorage` hook – Mulan Oct 11 '22 at 14:54

2 Answers2

0

Because you are never providing localStorage value to useState initially. Here is one approach. Pass initializer function to useState which is called only once.

let [lovepic, setlovepic] = useState(() => {
 const data = localStorage.getItem('k')

 if (data === null) return []

 return JSON.parse(data)
});

Javokhir
  • 228
  • 6
  • thanks for response, but it still can not work ,use this code can save the data in localstorage first time, if I refresh web, then click button , and refresh in localstorage, the data on first time to save would covered by second time . – coolboy Oct 11 '22 at 15:28
-1

As you are not getting items from localstorage whenever data changes/initial rendering of component render that is why it's not working as expected you can replace useEffect with following code

useEffect(() => {
  savelove();
},[data]);

And need to update couple of things in your save love function

 const savelove = () => {
    let mylist = localStorage.getItem("k");
    if (mylist == null) {
      setlovepic(data);
      localStorage.setItem("k", JSON.stringify([data]));
    } else {
      let listarr = JSON.parse(mylist);
      listarr.push(data);
      setlovepic(listarr);
      localStorage.setItem("k", JSON.stringify(listarr));
    }
  };
Prashant Shah
  • 226
  • 1
  • 8
  • thanks for response , but I try to use this code, it still not work, if I use this code, when I refresh the web, and refresh localstorage , it would show a lot of items in localstorage, sorry ,I am a root student , maybe the beginning code i write is wrong. – coolboy Oct 11 '22 at 15:11
  • If possible can you share more info or maybe codesandbox link – Prashant Shah Oct 11 '22 at 15:40