Search code examples
reactjsdatamodel

Reactjs JSON data into model class


Web API Service some columns do not return from service. For this reason, the columns I use on the front face can get the undefined error. Because if a field is empty it does not return from service. This is a company rule and i can't change it!

I can add columns that are not in the data. But I don't want to do this because of the performance. Because more records can come from the service

Can data modeling be done with ReactJS? How can I do it?

Data returned from Web API service:

[
  {
    "approvementType": "Waiting Approvement",
    "processName": "update",
    "screeName": "XYZ",
    "customerNo": 12345,
    "customerAccountNo": 12345,
    "customerName": "Paul",
    "description": "updating data"
   },
   {
    "processName": "insert",
    "screeName": "ABC",
    "customerNo": 12345,
    "customerName": "Alex",
    "description": "inserting data"
   }
   {
    "approvementType": "Complete Approvement",
    "customerNo": 987,
    "customerName": "Kane",
    "customerAccountNo": 0,
    "description": "complete data",
   }
]

Should be the result after data modeling:

[
  {
    "approvementType": "Waiting Approvement",
    "processName": "update",
    "screeName": "XYZ",
    "customerNo": 12345,
    "customerAccountNo": 12345,
    "customerName": "Paul",
    "description": "updating data"
   },
   {
    "approvementType": "",
    "processName": "insert",
    "screeName": "ABC",
    "customerNo": 12345,
    "customerAccountNo": 0,
    "customerName": "Alex",
    "description": "inserting data"
   }
   {
    "approvementType": "Complete Approvement",
    "processName": "",
    "screeName": ""
    "customerNo": 987,
    "customerName": "Kane",
    "customerAccountNo": 0,
    "description": "complete data",
   }
]

Solution

  • If the property is not inside the response the front side does not know about the property in this case you need to add to your object manually or you can use TypeScript with your react app for strongly type support and create interfaces for your models

    this link shows how to wire up TypeScript with React

    https://www.typescriptlang.org/docs/handbook/react-&-webpack.html