rstorms
November 3, 2020, 6:10pm
21
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.
rstorms
November 3, 2020, 6:20pm
23
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
rstorms
November 3, 2020, 6:23pm
25
Doesn’t help I already get paid to do this stuff. I’m such a hack hahaha. I’ll try to make that change.
rstorms
November 3, 2020, 6:26pm
26
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);
};
Looking good! Congratulations, and happy coding!
rstorms
November 3, 2020, 6:29pm
30
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
rstorms
November 3, 2020, 6:32pm
32
Yeah definitely, thank you very much again. I feel like such a goof with trivial things like this.
rstorms
November 3, 2020, 7:05pm
33
@ArielLeslie , thank you again. Got it all working as expected.