Search code examples
jsonreactjsfetchstate

Parsing JSON response in React to State


I have an API, which sends me a JSON and I want to populate my state with it, but some variable names are different. Do I have to do everything separately or is there a method to do all of them at once?

My JSON from request:

{
   "name":"julps",
   "place": "house",
   "number":"555032",
   ...
   "products":[
      {
         "name":"name1",
         "id":"123456"
      },
      {
         "name":"name2",
         "id":"234567"
      }
   ],
}

My state:

this.state = {
  name: '',
  place: '',
  phone: '',
  ...
  things: []
};

And the fetch request:

  fetchEditData = (code) => {
    installationDocumentRequestApi(`/${code}`)
      .then((importedJson) => {
        if (importedJson != null) {
          this.setState({
            name: importedJson.name,
            place: importedJson.place,
            phone: importedJson.number,
            ...
            things: importedJson.products
          });
        }
      });
  };

In this example it would be fine to do them separately but in my actual example I have around 20 fields so I started wondering if there is a shorter way to do it or its the only possible solution. Also If I could for example have all the same names then would it work without setting them separately?


Solution

  • Do I have to do everything separately or is there a method to do all of them at once?

    You do not have to do everything separately. And yes you have a way to get all of them at once.

    I recommend you to make a state with all of your data. You will then access your data through that.

    For exemple :

    this.state = {
      data: null
    };
    
    ... 
    
    fetchEditData = (code) => {
        installationDocumentRequestApi(`/${code}`)
          .then((importedJson) => {
            if (importedJson != null) {
              this.setState({
                data: importedJson
              });
            }
          });
      };
    

    And you can then get you data with your state. Like this for exemple console.log(data.name).

    As @evolutionxbox mentionned in comment it is maybe better for you to use the spread syntax this.setState({ ...importedJson })