Reputation: 1266
I am working on a React Native app where i am adding API response data to AsyncStorage. I am sending multiple API requests and need to add every response to previously stored AsynStorage data. I have tried AsyncStorage.mergeItem('key',JSON.stringify(data))
. But this is adding all data to one object only. I want every object seperately to be added.
Here's my sample API response:
{data: [{type: "noun",
definition: "a domesticated carnivorous mammal that typically has a long snout, an acute sense of smell, non-retractile claws, and a barking, howling, or whining voice.",
example: "she went for long walks with her dog"
}]
}
Now, i am saving this to AsyncStorage like this:
var data = response.data
await AsyncStorage.setItem('favourites', JSON.stringify(data));
Finally if i have a different response i want to add that to previous data like this:
[ {type: "noun",
definition: "a domesticated carnivorous mammal that typically has a long snout, an acute sense of smell, non-retractile claws, and a barking, howling, or whining voice.",
example: "she went for long walks with her dog"
},
{type: "noun",
definition: "a domesticated carnivorous mammal that typically has a long snout, an acute sense of smell, non-retractile claws, and a barking, howling, or whining voice.",
example: "she went for long walks with her dog"
}
]
How can i do that?
Upvotes: 1
Views: 113
Reputation: 61
you can try this code
var data = response.data
AsyncStorage.getItem('favourites')
.then((favourites) => {
const prevData = JSON.parse(favourites);
const newData = favourites ? [...prevData,...data] : [];
AsyncStorage.setItem('favourites', JSON.stringify(newData));
});
Upvotes: 1