Home > front end >  persisting the state of like button after refresh
persisting the state of like button after refresh

Time:01-17

I have an array of products that I fetched from APIs and it works perfectly. I map the array in ProductList page and prop drill each element to ProductListItem page. In that page I have rows of cards and each card has a like button from npm react-heart. What I want is to keep the state of the button after refreshing the page. There is no login or user. I think I need to use useEffect but after refreshing the page it doesnt work properly,thx

ProductListingPage.js

const ProductList = () => {
 
  return (

    <>
      <div>
        {products.map((e) => (
          <ProductListItem product={e} key={e.id}  />
        ))}
      </div>
    </>
  );
};

export default ProductList;

ProductListItem.js

import Heart from "react-heart";


const ProductListItem = ({ product}) => {
  const [active, setActive] = useState(false);

  useEffect(() => {
    const data = window.localStorage.getItem("key");
    setActive(data);
  }, []);

  useEffect(() => {
    window.localStorage.setItem("key", active);
  }, [active]);

  return (
    <>
      <div >
        <div >
          <img
            src={product.img_src}
            
            alt="Hollywood Sign on The Hill"
          />
          <div >
            <h5 >Card title</h5>
            <div style={{ width: "1rem" }}>
              <Heart isActive={active} onClick={() => setActive(!active)} />
            </div>
          </div>
        </div>
      </div>
    </>
  );
};

export default ProductListItem;

CodePudding user response:

The best way to go about this is to create a file to place a useLocalStorage custom hook. You should be able to copy and paste the following:

import { useState, useEffect } from "react";

function getStorageValue(key, defaultValue) {
  // getting stored value
  const saved = localStorage.getItem(key);
  const initial = JSON.parse(saved);
  return initial || defaultValue;
}

export const useLocalStorage = (key, defaultValue) => {
  const [value, setValue] = useState(() => {
    return getStorageValue(key, defaultValue);
  });

  useEffect(() => {
    // storing input name
    localStorage.setItem(key, JSON.stringify(value));
  }, [key, value]);

  return [value, setValue];
};

Then in your ProductListItem component. You want to import the useLocalStorage custom hook and use that in lieu of the useState hook like so:

import { useLocalStorage } from '[whereverYouPlaceThisFile]'

const [active, setActive] = useLocalStorage("active", "false")
  •  Tags:  
  • Related