Search code examples
javascriptcssreactjslocal-storageredux-toolkit

How do I use useEffect to save a background color state?


I am trying to save the background colour of my wishlist toggle button so that when the user travels across pages the colour of button remains "black" to show the user they have already saved the item to their wishlist.

const Item = (props) => {
  const dispatch = useDispatch();
  const [background, setBackground] = useState(false);

  function addToCartHandler(product) {
    dispatch(addToCart(product));
  }

  function toggleWishlistHandler(product) {
    dispatch(toggleItem(product));
    setBackground((current) => !current);
  }

  return (
    <div>
      <li className={classes.item}>
        <img src={props.img} alt="Item" className={classes.image} />
        <div className={classes.description}>
          <p className={classes.title}>{props.title}</p>
          <p className={classes.price}>£{props.price}.00</p>
        </div>
        <div className={classes.actions}>
          <div
            className={`${classes.addWishlist} ${classes.icon}`}
            onClick={() => toggleWishlistHandler(props.product)}
            style={{
              backgroundColor: background ? "black" : "orange",
            }}
          >
            <i className="fa-solid fa-heart"></i>
          </div>
          <div
            className={`${classes.addCart} ${classes.icon}`}
            onClick={() => addToCartHandler(props.product)}
          >
            <i className="fa-solid fa-bag-shopping"></i>
          </div>
        </div>
      </li>
    </div>
  );
};

export default Item;

Solution

  • You can save the color in local storage.

    // Check if it's set to black
      const [background, setBackground] = useState(localStorage.getItem('wishlistBackground') === 'black');
    
    
    // Save the background color to local storage whenever it changes
      useEffect(() => {
        localStorage.setItem('wishlistBackground', background ? 'black' : 'orange');
      }, [background]);