Search code examples
node.jsreactjssetstate

How can I update the array of objects from a fetch response


I tried a lot of things based on the other questions, but I didnt figured it how to do it.

I have this array in my component constructor:

 testDependeciesArr:[]

When the user clicks on button "test dependencies" of my react component I call this function:

testDependencies() {
    axios.get(process.env.REACT_APP_HOST + '/testDependencies')
      .then(resp => {
        this.setState(
          { testDependeciesArr: how to update this Array  }
          )

      })
      .catch(function (error) {
        console.log(error)
      })
  }

That function makes a request to nodejs and it returns me this:

{0: {…}, 1: {…}, 2: {…}}
    0:
    responseTime: "21ms"
    responseStatus: "OK"

    1:
    responseTime: "2739ms"
    statusText: "OK"

    2:
    responseError: {message: "request to http:url failed, reason: connect ECONNREFUSED 100.100.100.100:80", type: "system", errno: "ECONNREFUSED", code: "ECONNREFUSED"}
    responseTime: "10ms"

So, how can I update the array testDependeciesArr with the 3 objects that I get from the node response?

This table should be updated when I set the state:

API  Response Time  StatusDetail
API1    21ms          OK
API2    2739ms        OK
API3    21ms        request to http:url failed, reason: connect ECONNREFUSED 100.100.100.100:80", type: "system", errno: "ECONNREFUSED", code: "ECONNREFUSED

Solution

  • You can take advantage of Object.values():

    const res = {
      0: {
          responseTime: "21ms",
          responseStatus: "OK"
         },
    
     1:  {
          responseTime: "2739ms",
          statusText: "OK"
         },
    
     2: {
        responseError: {
          message: "request to http:url failed, reason: connect ECONNREFUSED 100.100.100.100:80", type: "system",
          errno: "ECONNREFUSED", code: "ECONNREFUSED"},
        responseTime: "10ms"
        }
    };
    
    
    console.log(Object.values(res));

    So, in your code:

    testDependeciesArr: Object.values(resp)