Home > Back-end >  React use useState to save to localstorage
React use useState to save to localstorage

Time:10-11

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;

CodePudding user response:

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)
});

CodePudding user response:

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));
    }
  };
  • Related