I have the following Object array stored using AsyncStorage:
[
{
"groupId": 1,
"id": 1,
"name": "a",
},
{
"groupId": 2,
"id": 2,
"name": "ab",
},
{
"groupId": 3,
"id": 3,
"name": "abc",
},
{
"groupId": 2,
"id": 4,
"name": "abcd",
},
]
I'm retrieving the data to display it in a Flatlist but instead of displaying the groupId, I would like to display the groupName for each item.
I have another key with groups stored:
[
{
"groupName": "g1",
"id": 1,
},
{
"groupName": "g2",
"id": 2,
}
]
I made a function to retrieve the groupName based on groupId. This works fine:
const getGroupName = async (groupIdToFind) => {
const existingsGroups = (await AsyncStorage.getItem("groups")) || "[]";
const existingsGroupsParsed = JSON.parse(existingsGroups);
const groupDataFound = existingsGroupsParsed.find(
(results) => results.id.toString().indexOf(groupIdToFind) > -1
);
if (groupDataFound) {
return groupDataFound.groupName;
}
return false;
};
And I thought of modifying the data retrieved from the storage in my loadFlatlist function but this is where I'm struggling.
const loadFlatlist = async (storageKey) => {
try {
let itemsOnStorage = await AsyncStorage.getItem(storageKey);
itemsOnStorage = JSON.parse(itemsOnStorage);
if (itemsOnStorage !== null) {
let finalItemsOnStorage = "";
itemsOnStorage.map(async function (obj) {
console.log(obj.groupId); // Correctly returns 1, 2, 3 ...
let retrievedGroupName = await getGroupName(obj.groupId);
console.log(retrievedGroupName); // Correctly returns g1, g2 ...
finalItemsOnStorage = await update(itemsOnStorage, {
groupId: { $set: retrievedGroupName },
});
});
console.log(finalItemsOnStorage); // Returns same content as itemsOnStorage
setDataOnDevice(itemsOnStorage); // This will be loaded in my flatlist
}
} catch (err) {
alert(err);
}
};
The problem is in loadFlatlist, I did not manage to replace the groupId by the groupName. finalItemsOnStorage has the same content as itemsOnStorage.
Can you see what is wrong with my function? Is there a better way to do this?