I'm trying to include a favorites mechanism to my react native codes, but I'm facing a problem:
When the page renders first, favs.includes
function works as expected. But when I clicked the favorite button, it raises an error
TypeError: favs.includes is not a function. (In 'favs.includes(id)', 'favs.includes' is undefined)
const getFavs = async () => {
await AsyncStorage.getItem("favs").then((res) => {
if (res !== [] && res !== null && res !== "") {
return setFavs(JSON.parse(res));
} else {
return setFavs([]);
}
});
};
useEffect(() => {
getFavs();
console.log(favs.includes(id));
return console.log(typeof favs);
}, []);
return (
<View style={{ alignItems: "center", justifyContent: "center" }}>
{favs.includes(id) ? (
<TouchableOpacity
onPress={() => {
AsyncStorage.removeItem("favs", id);
}}
>
<Icon name="star" size={25} color="orange" solid />
</TouchableOpacity>
) : (
<TouchableOpacity
style={{ height: 100, width: 100, backgroundColor: "red" }}
onPress={() => {
console.log(typeof favs);
setFavs(favs.push(id));
console.log(typeof favs);
AsyncStorage.setItem("favs", JSON.stringify(favs));
setFav(true);
}}
>
<Icon name="star" size={25} color="orange" />
</TouchableOpacity>
)}
</View>
);