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:
I first declare an array with index values, as such:
const dataArray= [ { data1:'', data2:'', } ];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:
- I first create the constructor:
constructor(props){
super(props);
this.state = {
data: dataArray,
}
}
- 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};