diff --git a/src/CacheContext.js b/src/CacheContext.js index 02e0425..30a2105 100644 --- a/src/CacheContext.js +++ b/src/CacheContext.js @@ -1,12 +1,14 @@ -import React, { useEffect, useReducer, createContext } from 'react'; +import React, { useEffect, useReducer, createContext } from "react"; + +const initialState = JSON.parse(localStorage.getItem("JIKAN_CACHE")) || {}; export const CacheContext = createContext(); -CacheContext.displayName = 'Cache'; +CacheContext.displayName = "Cache"; const cacheReducer = (state, action) => { const { type, payload } = action; switch (type) { - case 'SET_CACHE': + case "SET_CACHE": return { ...state, [payload.key]: payload.value, @@ -17,17 +19,18 @@ const cacheReducer = (state, action) => { }; export function CacheProvider({ children }) { - const [state, dispatch] = useReducer( - cacheReducer, - JSON.parse(localStorage.getItem('JIKAN_CACHE')) - ); + const [state, dispatch] = useReducer(cacheReducer, initialState); useEffect(() => { const serializedState = JSON.stringify(state); - localStorage.setItem('JIKAN_CACHE', serializedState); + localStorage.setItem("JIKAN_CACHE", serializedState); }, [state]); - return {children}; + return ( + + {children} + + ); } // Sin hooks para mostrar que es posible