I am learning react. And I am trying to setState on componentDidMount() function with external file contains Array of Data but it is not setting up the state. It shows empty every time I refresh the page.
app.js
import './App.css';
import React from 'react';
import newData from './data.js';
class App extends React.Component {
constructor(props) {
super(props)
this.state = {
data : []
}
}
componentDidMount() {
this.setState({data: newData});
console.log(this.state.data)
}
render(){
return (
<div>Hello</div>
)
}
}
data.js
const newData = [
{
"id": 1,
"name": "GoodName",
},
]
export default newData
I have also tried by changing the format of data and wrap into a a Seed.function like
window.Seed = (function() {
const newData = [
{
id: 1,
name: 'GoodName',
},
];
return {newData: newData };
}());
And tried to setState by
this.setState({data: Seed.newData});
But it says, Seed is not defined
-
Should I need to import external json array file in
index.htmlinstead of App.js ? -
Should I need to use
mapfunction orfor ofloop to iterate every element in data before setting state ?
I have tried many times but it is still not working.
Any help would be much Appreciated. Thank You in Advance.
>Solution :
this.state.data is not immediately available after calling setState. Check:
https://reactjs.org/docs/faq-state.html#why-doesnt-react-update-thisstate-synchronously
Try to stick console.log in render instead to see the contents of an array.