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

116
Vistas
Appending data to AsyncStorage

I am trying to append an Object to an existing array of objects in AsyncStorage, however not being successful. Any help is appreciated!

Current code:

const [storageItems, setStorageItems] = useState([]);

 const handleHabitCreation = async () => {
        setLoading(true);

        const newHabit = {
            name: name,
            color: updatedColor,
            days: daysCount,
            times: timesCount,
            reminder: selectedDate,
            description: description,
        };

        try {
            const jsonValue = await AsyncStorage.getItem('@habit');
            setStorageItems(jsonValue);
        } catch (error) {
            console.error(error);
        }

        const stringifiedHabit = JSON.stringify(newHabit);
        setStorageItems([...storageItems, stringifiedHabit]);

        try {
            await AsyncStorage.setItem('@habit', JSON.stringify(storageItems));
            setTimeout(() => {
                setLoading(false);
                navigation.pop(3);
            }, 2500);
        } catch (error) {
            console.error(error);
        }
    };

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

The proplem is that you are not parsing the stringified json data. You need to parse it to perform any modification. Save the data in the state as parsed json and srtingify it just before saving it to the async storage. Try this code:

try {
    const jsonValue = await AsyncStorage.getItem('@habit');

    // saving parsed json
    const data = JSON.parse(jsonValue)
    setStorageItems(data);
} catch (error) {
    console.error(error);
}
// state depends on previous state
setStorageItems((prevState) => [...prevState, newHabit]);

or to make shorter

try {
    const jsonValue = await AsyncStorage.getItem('@habit');
    let data = JSON.parse(jsonValue) // parse to modify

    // push newHabit as well
    data.push(newHabit)

    setStorageItems(data);
} catch (error) {
    console.error(error);
}

in both approaches, stringify the object in the end

await AsyncStorage.setItem('@habit', JSON.stringify(storageItems));
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