Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

308
Vistas
after using React Natives usestate function, includes method fails

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>
);
about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

The problem lies in this line in your click handler

setFavs(favs.push(id))

which sets favs to a number not an array. Array#push() returns the new length of the array after push, not the array itself. see Why does Array.prototype.push return the new length instead of something more useful?.

Also, using push() on a state array mutates the array, you should instead

setFavs(prevFavs => [...prevFavs, id])
// or
setFavs(prevFavs => prevFavs.concat(id))

Your last error is assuming that calling console.log after your setState call will reflect the change in state when it will in fact log the old(current) state value. The updated state value won't be available until the next render cycle. see Why calling react setState method doesn't mutate the state immediately?

about 4 years ago · Juan Pablo Isaza Denunciar

0

I think it is usually because of when the component rendered at first, favs state is still empty or getFavs async function wasn't finished.

Maybe you can try to give condition to where favs.includes invoked such as:

           {favs && favs.includes && favs.includes(id)? // make sure favs is truthy and favs.includes property existed
            <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 >
            }

Please let me know if this solve your issue or not, thanks

about 4 years ago · Juan Pablo Isaza Denunciar

0

I see two problems with your code.

Firstly, I do not see your useState usage. It should be

const [favs, setFavs] = useState([]);

Secondly, you are mixing asynchronous and synchronous code. You are calling getFavs, which contains a call to asynchronous storage which is executed "outside" of main program thread. And immediately after that you are calling favs.includes(), which of course will not work, because the async call did not come through yet.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda