Home > Software design >  The setItem function is working fine in Reactjs but localStorage.getItem is not working
The setItem function is working fine in Reactjs but localStorage.getItem is not working

Time:10-16

In the code I change some recipe content and it saves but when I refresh my page it resets everything and the changes are gone

Here is my code

const LOCAL_STORAGE_KEY = "cookingWithKyle.recipes"

function App() {
  const [selectedRecipeId, setSelectedRecipeId] = useState()
  const [recipes, setRecipes] = useState(sampleRecipe)
  const selectedRecipe = recipes.find(
    (recipe) => recipe.id === selectedRecipeId
  )

  useEffect(() => {
    const recipeJSON = localStorage.getItem(LOCAL_STORAGE_KEY)
    if (recipeJSON) setRecipes(JSON.parse(recipeJSON))
  }, [])

  useEffect(() => {
    localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(recipes))
  }, [recipes])

CodePudding user response:

AFAIK, in React useEffect hook's callback is run asynchronously. So, you cannot control which callback is processed first and end before another.

But here, the main reason of your issue is, even if you have recipes as a dependency in your second useEffect, second useEffect's callback will also be fired on initial mount (on page reload), thus in your code you set a value (probably undefined) to your localStorage and then try to get a value, which was already gone. So, try to run your second useEffect's callback with a condition:

useEffect(() => {
   if (recipes) {
       localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(recipes))
   }
}, [recipes])

For information, React fires the useEffect hooks callback when it compares dependency list in an array with a previous render (so, try not to use a value of object type as a dependency, otherwise your callback will be fired in every render) and if it sees the difference, it fires useEffect's callback, including the initial render.

  • Related