title: Cart funcionality using Context Api
body: <p>I am trying to achieve cart functionality, but I want to save the cart on the refresh of the page. Anyway, the problem is this I have Context Api and cart logic (add to cart, removeitem, amount, setCartItem) so when I try to add an item to the cart, nothing happens, and when I check the cart nothing is in there. I know this question has a lot of code, and the mistake could be anywhere, if someone could help I would be really grateful.</p>
  <p>Cart Context</p>
  <pre><code>
  import React from &quot;react&quot;;
  
  function getCartFromLocalStorage() {
    return localStorage.getItem(&quot;cart&quot;)
      ? JSON.parse(localStorage.getItem(&quot;cart&quot;))
      : [];
  }
  
  const CartContext = React.createContext();
  
  function CartProvider({ children }) {
    const [cart, setCart] = React.useState(getCartFromLocalStorage());
    const [total, setTotal] = React.useState(0);
    const [cartItems, setCartItems] = React.useState(0);
  
    React.useEffect(() =&gt; {
      localStorage.setItem(&quot;cart&quot;, JSON.stringify(cart));
  
      let newTotal = cart.reduce((total, cartItem) =&gt; {
        return (total += cartItem.amount * cartItem.price);
      }, 0);
      newTotal = parseFloat(newTotal.toFixed(2));
      setTotal(newTotal);
  
  
      let newCartItems = cart.reduce((total, cartItem) =&gt; {
        return (total += cartItem.amount);
      }, 0);
      setCartItems(newCartItems);
    }, [cart]);
  
  
    const removeItem = key =&gt; {
      setCart([...cart].filter(item =&gt; item.key !== key));
    };
  
   
    const addToCart = book =&gt; {
      const { key, image, bookName, by  } = book;
      const item = [...cart].find(item =&gt; item.key === key);
    }
     
    const clearCart = () =&gt; {
      setCart([]);
    };
    return (
      &lt;CartContext.Provider
        value={{
          cart,
          cartItems,
          total,
          removeItem,
          addToCart,
          clearCart
        }}
      &gt;
        {children}
      &lt;/CartContext.Provider&gt;
    );
  }
  
  export { CartContext, CartProvider };
  </code></pre>
  <p>Books</p>
  <pre><code>import React,{useContext} from 'react'
  import { CartContext } from '../../context/cart';
  import HoverBooks from './HoverBooks';
  import { useHistory } from &quot;react-router-dom&quot;;
  const Books = ({category}) =&gt; {
  const {addToCart }= useContext(CartContext)
      return (     
          &lt;div className='books__main'&gt;      
          {category.slice(0, 5).map((book) =&gt; {       
            return(
              &lt;&gt;
             &lt;HoverBooks 
             key={book.key}
             {...book}       
             /&gt;    
             &lt;div className='book__content'&gt;
              &lt;li&gt;{book.bookName}&lt;/li&gt;
               &lt;h4&gt;By{book.by}&lt;/h4&gt;
               &lt;h4&gt;Narreted by:{book.Narreted}&lt;/h4&gt;
               &lt;h4&gt;Length: {book.length}&lt;/h4&gt;
               &lt;h4&gt;Release Date: {book.ReleaseDate}&lt;/h4&gt;
               &lt;h4&gt;Language: {book.Language}&lt;/h4&gt;
               &lt;h4&gt;{book.rating}&lt;/h4&gt;
             &lt;/div&gt;           
             &lt;div&gt; 
           &lt;span&gt;Regular Price: {book.RegularPrice}&lt;/span&gt;
             &lt;button onClick={() =&gt; {
                addToCart(book);
              }}
             &gt;Add to cart&lt;/button&gt;  
             &lt;/div&gt;
         &lt;/&gt;
          )})}
        &lt;/div&gt;
      )
  }
  
  export default Books
  </code></pre>
  <p>Cart</p>
  <pre><code>import React from &quot;react&quot;;
  import { Link } from &quot;react-router-dom&quot;;
  import EmptyCart from &quot;./EmptyCart&quot;;
  import CartItem from './CartItem'
  import { UserContext } from &quot;../../context/user&quot;;
  import { CartContext } from &quot;../../context/cart&quot;;
  import './Cart.css'
  export default function Cart() {
    const { cart, total } = React.useContext(CartContext);
    const { user } = React.useContext(UserContext);
    if (cart.length === 0) {
      return &lt;EmptyCart /&gt;;
    }
    return (
      &lt;div className=&quot;cart__items&quot;&gt;
        &lt;h2&gt;your cart&lt;/h2&gt;
        {cart.map(item =&gt; {
          return &lt;CartItem key={item.key} {...item} /&gt;;
        })}
        &lt;h2&gt;total : ${total}&lt;/h2&gt;
        {user.token ? (
          &lt;Link to=&quot;/cart&quot; className=&quot;btn&quot;&gt;
           
          &lt;/Link&gt;
        ) : (
          &lt;Link to=&quot;/login&quot; className=&quot;btn&quot;&gt;
            login
          &lt;/Link&gt;
        )}
      &lt;/div&gt;
    );
  }
  </code></pre>
  <p>Cart Item</p>
  <pre><code>import React, { useContext } from &quot;react&quot;;
  import { CartContext } from &quot;../../context/cart&quot;;
  export default function CartItem({ key, image,bookName, amount }) {
    const {removeItem} = useContext(CartContext)
    return (
      &lt;div className=&quot;cart__item&quot;&gt;
        &lt;img src={image}  /&gt;
        &lt;div&gt;
          &lt;h4&gt;{bookName}&lt;/h4&gt;
          &lt;h5&gt;${by}&lt;/h5&gt;
          &lt;button
            className=&quot;cart__removebtn&quot;
            onClick={() =&gt; {
              removeItem(key);
            }}
           &gt;
            remove
          &lt;/button&gt;
        &lt;/div&gt;
          &lt;p className=&quot;item__amount&quot;&gt;{amount}&lt;/p&gt;
      &lt;/div&gt;
    );
  }
  
  </code></pre>
  <p>Cart Link</p>
  <pre><code>import React from &quot;react&quot;;
  import { Link } from &quot;react-router-dom&quot;;
  import {FiShoppingCart} from 'react-icons/fi'
  import { CartContext } from &quot;../../context/cart&quot;;
  export default function CartLink() {
  
    const { cartItems } = React.useContext(CartContext);
    return (
      &lt;div className=&quot;cartlink__container&quot;&gt;
        &lt;Link to=&quot;/cart&quot;&gt;
        &lt;FiShoppingCart /&gt;
        &lt;/Link&gt;
        &lt;span className=&quot;cartlink__total&quot;&gt;{cartItems}&lt;/span&gt;
      &lt;/div&gt;
    );
  }
  </code></pre>
  <p>Home</p>
  <pre><code>import React,{useState, useEffect, useContext} from 'react'
  import './Home.css'
  import Books from './Books'
  import { BookContext } from &quot;../../context/books&quot;;
  const Home = () =&gt; {
     const {data, handleSelectCategory, currentSelectedCategory } 
      =useContext(BookContext)
      return (
          &lt;div className='books__container' &gt;
            &lt;h1 className='categories'&gt;Categories&lt;/h1&gt;
              {Object.keys(data).map((key, index)=&gt;{
              let books = data[key];
              return (
                &lt;&gt; 
                &lt;span key={key} onClick={() =&gt; handleSelectCategory(key)} 
                className='books__list' &gt;
                {books[0].category}
                &lt;/span&gt;         
               &lt;/&gt;
                );})}
                &lt;Books category={currentSelectedCategory} /&gt;
          &lt;/div&gt;
      )
  }
  export default Home
  </code></pre>
  <p>book</p>
  <pre><code>import React, {useState, useEffect} from 'react'
  import URL from '../utilis/URL';
  const BookContext = React.createContext();
  export default function BooksProvider({ children }) {
    
    const [data, setData] = useState([])
    const [currentSelectedCategory, setCurrentSelectedCategory] = useState([]);
  
    const handleSelectCategory = (category) =&gt; {
      setCurrentSelectedCategory(data[category]);
    };
    
    const fetchData = async () =&gt; {
      const response = await fetch(URL);
      const result = await response.json();  
      console.log(result)
      setCurrentSelectedCategory(result[Object.keys(result)[0]]);
      setData(result);
    };
  
    useEffect(()=&gt;{
      fetchData();
    },[])
  return (
      &lt;BookContext.Provider value={{ data, handleSelectCategory, setCurrentSelectedCategory, currentSelectedCategory }}&gt;
        {children}
      &lt;/BookContext.Provider&gt;
    );
  }
  export {BookContext, BooksProvider}
  </code></pre>