Updating react state in array?

  const addFavorite = (id) => {
    let newList = [...favorites];
    const foundId = newList.find((foundId) => foundId === id);

    if (!foundId) {
      newList.push(id);
    } else {
      newList.filter(pokemonId => pokemonId !== id)
    }

    setFavorites(newList);
  };

Slightly closer, now I just can’t get it to delete.

.filter() does not modify the array. It returns a new array.

  const addFavorite = (id) => {
    let newList = [...favorites];
    const foundId = newList.find((foundId) => foundId === id);

    if (!foundId) {
      newList.push(id);
    } else {
      let index = newList.indexOf(foundId);
      newList.splice(index, 1);
    }

    setFavorites(newList);
  };

I’m stupid this week. Thanks for the help lol. I might come back for questions with this custom hook for localstorage.

1 Like

Good job working through this! I know that it can be extremely overwhelming and frustrating. You powered through!

One more comment… You don’t need to do a .find() and then an .indexOf. You can just do the .indexOf() in the first place. it will return -1 if the item is not found in the array.

1 Like

Doesn’t help I already get paid to do this stuff. I’m such a hack hahaha. I’ll try to make that change.

Cool, slightly cleaned up:

  const addFavorite = (id) => {
    let newList = [...favorites];
    let foundId = newList.indexOf(id);

    if (foundId === -1) {
      newList.push(id);
    } else {
      newList.splice(foundId, 1);
    }

    setFavorites(newList);
  };

2 Likes

Hahahahahaha excellent

Looking good! Congratulations, and happy coding!

If you don’t mind, now I need to connect this state to this custom hook I have built out:

import { useState, useEffect } from 'react';

const useLocalStorage = (key, defaultValue) => {
  const [value, setValue] = useState(() => {
    let val;
    try {
      val = JSON.parse(window.localStorage.getItem(key) || defaultValue);
    } catch (e) {
      val = defaultValue
    }
  });

  useEffect(() => {
    window.localStorage.setItem(key, JSON.stringify(value));
  }, [key, value]);

  return [value, setValue];
}

export default useLocalStorage;

And use it like so:

const [favorites, setFavorites] = useLocalStorage('favorites', []);

  const addFavorite = (id) => {
    let newList = [...favorites];
    let foundId = newList.indexOf(id);

    if (foundId === -1) {
      newList.push(id);
    } else {
      newList.splice(foundId, 1);
    }

    setFavorites(newList);
  };

Any ideas?

I’m not a React dev, so I don’t know about react hooks and am no help. I know that there are many more qualified people here who hopefully can jump in and assist though.

1 Like

Yeah definitely, thank you very much again. I feel like such a goof with trivial things like this.

@ArielLeslie, thank you again. Got it all working as expected.

Congratulations :tada:

1 Like