Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

118
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda