Skip to content

Instantly share code, notes, and snippets.

@Sleavely
Created July 17, 2019 11:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Sleavely/0e75889d364e1ecf24d285ec97c5432e to your computer and use it in GitHub Desktop.
Save Sleavely/0e75889d364e1ecf24d285ec97c5432e to your computer and use it in GitHub Desktop.
import React, { useEffect, useState } from 'react'
import { CartProvider } from "use-cart"
import { LoadCart, SaveCart } from "./cartStorage"
function App() {
return (
<CartProvider initialCart={LoadCart()}>
<SaveCart />
<RestOfApp> ... </RestOfApp>
</CartProvider>
)
}
import React, { useEffect } from 'react'
import { useCart } from 'use-cart'
import storage from 'react-use/lib/useLocalStorage';
const getCartStorage = () => {
return storage(
'cart',
[]
)
}
// Regular function to be used inline
export const LoadCart = () => {
const [cart] = getCartStorage()
return cart
}
// Functional component to be placed under CartProvider
export function SaveCart() {
const { items } = useCart()
const [ , setCart ] = getCartStorage()
useEffect(() => {
setCart(items)
}, [ items ])
return (
<></>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment