Search code examples
reactjsformsauthenticationuser-input

Reactjs save and update the same user info with the same ID


This is my User Settings page.

I created a button that is used to save and edit the info.

I would like that once the info is saved the first time, the app would register the user ID in order to update the info instead of creating new lines in the database.

In the sandbox you find the code I wrote, but it doesn't work. In the sandbox it didn't work because obviously there is no back-end, but that's not the error I'm referring to. The problem I think is in the "services" folder and in this piece of code:

if (info.id === null) {
      InfoDataService.create(data)
        .then((response) => {
          console.log('create', response.data);
          setInfo({
            id: response.data.id,
            email: response.data.email,
            firstname: response.data.firstname,
            lastname: response.data.lastname
          });
        })
        .catch((e) => {
          console.error(e);
        });
    } else {
      InfoDataService.update(info.id, data)
        .then((response) => {
          console.log(response);
          setInfo({
            id: response.data.id,
            email: response.data.email,
            firstname: response.data.firstname,
            lastname: response.data.lastname
          });
          console.log(response.data);
        })
        .catch((e) => {
          console.error(e);
        });
    }
  };

Solution

  • Something like this should work: https://codesandbox.io/s/patient-glade-3z67y?file=/src/UserInfo.js

    I've mocked your API in infoService.js so it would at least do something, but you should be able to remove those lines and it will work locally for you.

    Hope this points you in the right direction!