Update array and Rendder new data in React.js

I have a problem with updating and rendering new data from an API-call.

The way I have set-up the code now is presented below:

JavaScript file to read the returned JSON from API-call:

  1. I first declare an array with index values, as such:

    const dataArray= [
      {
         data1:'',
         data2:'',
      }
    ];
    
  2. I have a function that parses the data from the API-call, and reassigns the new data the array, as such:

    dataArray.data1 = newData1;

Before the dataArray is exported from the JS-file:

export { dataArray }

The React-part is set up as follows:

  1. I first create the constructor:
  constructor(props){
    super(props);
    
    this.state = {
      data: dataArray,
    }
}
  1. Then, in the rendering, I create a const called data, and I set it this.state:
render(){
    const { temperatures } = this.state;

  return (  
    <div className="App">
      <Card        
        data1 = {  
          data.map(dataArray=> 
            <p key={data.data1}>
              {data.data1}
            </p>
            )
          }
       );
    };
  }
export default App;

And this works fine if I insert some arbitrary data dataArray in the JavaScript-file, but when new data is available, this new data is not rendered to the DOM.

I have dug a bit, and I understand that I need to use this.setState to update the DOM when new data is available, instead of this.state, but I am not sure where to use setState...

Regards, Hans-Kristian

The entire code is shown below: App.js

class App extends React.Component{
  constructor(props){
    super(props);
    
    this.state = {
      temperatures: forecastedTemperatures,
    }
    
}
  render(){
    const { temperatures } = this.state;
  return (  
    <div className="App">
      <Card       
        data1 = {  
          dataArray.map(data=> 
            <p key={data.data1}>
              {temperature.data1}
            </p>
            )
          }
      />
    </div>
  );
};
}
export default App;

callApiAndParse.js

import React, {Component} from 'react';
const fs = require('fs');

const dataArray= [
  {
    data1:'',
    data2:'',
   
  }
];

function parsionFunction(data1, data2
)
{  

    //This funciton just manipulated the data, and is outside the scope of this question

    dataArray.data1 = data1;
    dataArray.data1 = data2;
    
}

export { dataArray};

Upvotes: 0

Views: 1373

Answers (1)

Viraj Jadhav
Viraj Jadhav

Reputation: 119

You can use one of React's lifecycle methods -> componentDidMount(), Wherein you can call it in "async" fashion and "await" when your parsing is done, after that you can use this.setState(), to set you data variable to state. While it is happening you can even use a loading state, to improve your ui, so that user will get to know that some thing is being loaded.

Example:

lets say your original state variable in constructor was:

this.state = {
    dataArray = [],
    loading: true, // As component will be loading.
}

Then State change may happen something like this:

async componentDidMount() {
     try {
         const tempData = await parsingOfRecievedData(APICallFunction());
         this.setState(
            dataArray: tempData,
            loading: !this.state.loading, // Set to false, as prev value was true
         };
     } catch (error) {
          console.log(error.message);
          this.setState(
            loading: !this.state.loading, // Need to handle loading in case of errors / exceptions.
          );
     }
}

Upvotes: 1

Related Questions