I am using integers as object ids, whenever a new element is added, I increment the last id integer value in the list and assign it to the new added element’s id.
Adding items to my list and json db works just fine, but when trying to UPDATE the list (DELETE) it gives me a not found error 404.
I ultimately figured out it was because the assigned value to the IDs is an integer but not a string. But I need an integer value to increment and not a string, or else I have to parseInt the ID string from json file and then increment it then again convert it to a string in order to add new elements to the list.
I tried the following solution and it worked. But it seems redundant and probably not the best approach to fix this.
I have looked up this issue online, but There were no straight forward answers.
I would like to know why can’t json just accept an integer for a value? and is there a more efficient way to convert integer values to strings when added to a json object.
async function addItem(item) {
** const itemID = items.length ? (parseInt(items[items.length - 1].id) + 1).toString() : (1).toString();**
const newAddedItem = {
id: itemID,
isChecked: false,
item
}
const updatedListItems = [...items, newAddedItem];
setItem(updatedListItems);
//update the REST API
const postOptions = {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(newAddedItem)
}
const result = await apiRequest(API_URL, postOptions);
if (result) setFetchError(result);
}