Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

115
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!