I've created a fake JSON server using npm i json-server in my React application. I've created a db.json file and have created the following function to push a new 'task' to the server for persistence:
const addTask = async task => {
const res = await fetch(`http://localhost:5000/tasks`, {
method: 'POST',
headers: {
'Content-type': 'application/json'
},
body: JSON.stringify(task)
})
const data = await res.json()
setTasks([...tasks, data])
}
Now, this is how my db.json is being saved:
{
"tasks": [
{
"id": 1,
"text": "Doctors Appointment",
"day": "Feb 5th at 2:30PM",
"reminder": true
},
{
"text": "SWE Interview",
"day": "May 9th at 9:30AM",
"reminder": false,
"id": 2
},
{
"text": "School Meeting",
"day": "Feb 11th at 5:30PM",
"reminder": false,
"id": 3
}
]
}
id:1 has been manually entered and id:2 and id:3 have been POST'd in using the UI. How can I make it so that they follow the same pattern of arrangement as id:1 i.e. id, text, day then reminder?
Order of keys in JSON should not have any affect on the data. If you still need the object to be in a specific order, I would write custom function to stringify the JSON. Here's the code I came up with:
function stringifyTask(task) {
return `{
"id": ${task.id},
"text": "${task.text}",
"day": "${task.day}",
"reminder": ${task.reminder}
}`
}