0

I'm practicing fetch api and have problem with posting data... in first step I post to 'http://localhost:3003/users' and it works fine -> code:

(async () => {
        const res = await fetch('http://localhost:3003/users', {
          method: 'POST',
          body: JSON.stringify({ name, password }),
          headers: {
            'Content-Type': 'application/json'
          }
        });

but in another component (second step) I have this code:

  useEffect(() => {
    (async () => {
      try {
        const resp = await fetch(`http://localhost:3003/users/${userID}`, {
          method: 'POST',
          body: JSON.stringify({ tasks: [1, 2, 3] }),
          headers: {
            'Content-Type': 'application/json'
          }
        }).then(res => console.log(res));
      } catch (err) {
        console.error(err);
      }
    })();
  }, [userID]);

and after logging to the console, got this:

Response {type: "cors", url: "http://localhost:3003/users/0", redirected: false, status: 404, ok: false, …}
body: (...)
bodyUsed: false
headers: Headers {}
ok: false
redirected: false
status: 404
statusText: "Not Found"
type: "cors"
url: "http://localhost:3003/users/0"

But when I go to http://localhost:3003/users/0, I can see the user so it seems that url works... Of course when I delete ${userID} it works, but array is added as the last object, not to this specific user... What's more - http://localhost:3003/users/${userID} works with GET method.

The question is - how to post data to single object in array in JSON server??

db.json:

{
  "users": [
    {
      "id": 0,
      "name": "Ola",
      "password": "12345"
    },
    {
      "name": "newuser",
      "password": "newuser",
      "id": 1
    }
  ]
}

form submission checks if there is a user with this name; if not, post new user

Ola Kozioł
  • 95
  • 3
  • 10

2 Answers2

1

RESOLVED

I used wrong method - POST instead of PATCH

Ola Kozioł
  • 95
  • 3
  • 10
0

So when you are posting something, in your case you are posting it to the users array

so it should be try in this way

fetch(`http://localhost:3003/users`)

and in your body you need to pass the id

{ id:`${userId}` tasks: [1, 2, 3] }

Update these things and check.

OR

Update

As it is adding a new property to the user object need to use Patch instead of Post

You can read more on here

Learner
  • 8,379
  • 7
  • 44
  • 82