0

I have been trying to push an object into a state array and then into local storage so it can remain visible even after refreshing, everything works fine except final push doesent happen. In order for an object to stay saved in local i have to add it and one after it, and the one after dont get saved. Any help is much appreciated

function App() {
  const [data, setData] = useState([{ name: "", thumbnail: { path: "" } }]);
  const [team, setTeam] = useState(JSON.parse(localStorage.getItem("team")));
  console.log(team);
  useEffect(() => {
    fetch(
      "http://gateway.marvel.com/v1/public/characters?apikey="
    )
      .then((data) => data.json())
      .then((data) => setData(data.data.results));
  }, []);

  const addToTeam = (hero) => {
    !team ? setTeam([hero]) : setTeam([...team, hero]);
    localStorage.setItem("team", JSON.stringify(team));
  };

2
  • 1
    what doesnt work exactly? the localStorage or the setTeam? Commented Apr 27, 2021 at 16:57
  • they both work, except in order for first added object to be visible after refresh i need to add one after it, only then it stays in local storage. Its allways one step behind. Commented Apr 27, 2021 at 16:59

1 Answer 1

1

React state updates are not synchronous. So when you run this code:

  const addToTeam = (hero) => {
    !team ? setTeam([hero]) : setTeam([...team, hero]);
    localStorage.setItem("team", JSON.stringify(team));
  };

you could be setting previous value of team instead of the value you just set.

To fix the problem you can make a side effect that runs when the team state changes and update localStorage from it.

useEffect(() => {
  localStorage.setItem("team", JSON.stringify(team));
}, [team]);
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you good sir, today you taught me something. It works now :D
This should be marked as the correct answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.