Last active
May 1, 2020 17:24
-
-
Save Falci/0acfb7f53cb923ee34e3abbb2303b219 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useReducer } from "react"; | |
const stored = localStorage.getItem("data"); | |
const emptyStore = { ... }; | |
const initialState = (stored && JSON.parse(stored)) || emptyStore; | |
const reducer = (state, action) => { | |
switch (action.type) { | |
case "increment": | |
return { count: state.count + 1 }; | |
case "decrement": | |
return { count: state.count - 1 }; | |
default: | |
throw new Error('Unknown action type'); | |
} | |
}; | |
export const useStorage = () => { | |
const hook = useReducer(reducer, initialState); | |
localStorage.setItem("data", JSON.stringify(hook[0])); | |
return hook; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment