S
S
shmebulok2021-08-29 08:07:57
JavaScript
shmebulok, 2021-08-29 08:07:57

How to add a new element (object) to an array which is in an object using fetch/post?

Hello, to the point:
I am creating a ToDo web application, a project for myself, so to speak, for study. While working with fetch / post, a question arose for which I could not find a normal answer, and I decided to ask it here.
I have a db.json file which is located on a local server ( json-server )
like this:

{
  "usersTodos": [
    {
      "id": 1000,
      "todos": []
    }
  ]
}

As you can see there is a usersTodos array which has one object with id and todos array (by the way, the idea is that this array stores objects in the same way as usersTodos )
Using the fetch post method I can add a new object to usersTodos, but I want to add its not in usersTodos, but in the todos array.
fetch('http://192.100.0.0:3000/usersTodos', {
          method: 'post',
          headers: {
            'Accept': 'application/json, text/plain, */*',
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(obj)
        })

This code adds a new object to usersTodos
As I said above that todos stores objects, how can I use fetch to POST, add a new element to todos and is it possible?
I think I asked the question correctly, and it was more or less clear to you

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Sokolov, 2021-08-29
@shmebulok

because typicode /json-server
is used , you can apparently change the saved data by their id, with a PATCH request:

const obj = {
  todos: [
    {title: "QnA", description: "прочитать документацию"},
  ],
}
fetch('http://192.100.0.0:3000/usersTodos/1000', { // здесь 1000 это id
          method: 'patch',
          headers: {
            'Accept': 'application/json, text/plain, */*',
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(obj)
        })

To add, you must first pull out the saved record by id, and push a new one in its todos field.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question