Hi I am using axios to fetch JSON data in React, the issue is that I am not able to search within the fetched data.
I tried fetching the data in the parent component but the request is asynchronous so it loads child components first and then fetches data.
Below is my code :
axios.get("/url.json")
.then(function(result) {
teams= result.data.teams
});
ReactDOM.render(
<div>
<App teams={teams}/>
</div>
,document.getElementById('app')
)
If I fetch data using axios inside the child component how do I save the data for search? i.e I need to search in the unfiltered data.
Call ReactDOM.render
after request succeeding : I mean inside the callback of axios NOT out side.
axios.get("/url.json")
.then(function(result) {
const teams= result.data.teams;
ReactDOM.render(
<div>
<App teams={teams}/>
</div>
,document.getElementById('app')
)
});
..... OR.....
As BEST PRACTICES, you can add another layer (super-parent) which handles this call inside its componentDidMount :
class Root extends React.Component {
constructor() {
super(...arguments);
this.state= {teams : []};
}
componentDidMount() {
axios.get("/url.json")
.then((result) => {
this.setState({teams: result.data.teams})
});
}
render() {
return (
<div>
<App teams={this.state.teams}/>
</div>
)
}
}
ReactDOM.render(
<Root />
,document.getElementById('app')
)