This is my json-server database.
{
"users": {
"sarahedo": {
"id": "sarahedo",
"name": "Sarah Edo",
"avatarURL": "https://pluralsight.imgix.net/author/lg/6f77d113-ea36-4592-814d-9d4acb32f231.jpg",
"answers": {
"8xf0y6ziyjabvozdd253nd": "optionOne",
"6ni6ok3ym7mf1p33lnez": "optionOne",
"am8ehyc8byjqgar0jgpub9": "optionTwo",
"loxhs1bqm25b708cmbf3g": "optionTwo"
},
"questions": ["8xf0y6ziyjabvozdd253nd", "am8ehyc8byjqgar0jgpub9"]
},
}
I need to add new ID in "questions": ["8xf0y6ziyjabvozdd253nd", "am8ehyc8byjqgar0jgpub9"] but I can't access it in fetch URL.
I tried to check the URL in browser "HTTP://localhost:3000/users/sarahedo" I get empty object for some reason {}
I want to know how can I add new data to it using fetch POST.
The reason that you get an empty object from http://localhost:3000/users/sarahedo is that you've defined your data in .json file incorrectly. If you correct your .json file with the below data, you'll see your user obj by hitting http://localhost:3000/users/sarahedo in the browser.
{
"users": [
{
"id": "sarahedo",
"name": "Sarah Edo",
"avatarURL": "https://pluralsight.imgix.net/author/lg/6f77d113-ea36-4592-814d-9d4acb32f231.jpg",
"answers": {
"8xf0y6ziyjabvozdd253nd": "optionOne",
"6ni6ok3ym7mf1p33lnez": "optionOne",
"am8ehyc8byjqgar0jgpub9": "optionTwo",
"loxhs1bqm25b708cmbf3g": "optionTwo"
},
"questions": [
"8xf0y6ziyjabvozdd253nd",
"am8ehyc8byjqgar0jgpub9"
]
}
]
}
You can either use below code for adding new data, using fetch POST:
async function postData(url = '', data = {}) {
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
return response.json()
}
For more detailed info about fetch POST, check this out: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#supplying_request_options