Answer the question
In order to leave comments, you need to log in
What is the best way to update data from the API?
Good evening, I recently started learning ReactJS and I have a question...
When I open a page, I receive data via componentDidMount , but when I follow a link (router) to another page of the same component, then the data is updated using componentDidUpdate .. So here's the question... When I go to the page, componentDidUpdate is constantly requesting data... how do I request data only 1 time? The only thing I've come up with so far is to check the URL , but maybe there is a more elegant solution?
constructor(props) {
super(props);
this.state = {
module: [],
materials: []
};
}
getData() {
var name = this.props.name;
axios.post('/api/modules/'+ name, {
'jsonrpc': '2.0'
})
.then(response => {
this.setState({ module: response.data.result, materials: response.data.result.materials });
})
.catch(function (error) {
});
}
componentDidMount() {
this.getData();
}
componentDidUpdate(prevProps) {
if (this.props.match.params.name !== prevProps.match.params.name) {
this.getData();
}
}
Answer the question
In order to leave comments, you need to log in
Making the isNeedUpdate flag can be done.
Maybe for the route you need to load new data. Therefore, it is normal to constantly request new data. If not the norm, then I would request data only when I am sure that they can be updated and new data is needed for the component that will appear on the Route.
So I often saw on projects that the data is cached. If forceUpdate does not come to the getData function, then the cache of the store is looked up.
Why not put this request in the route? Let him load the data he needs.
Read about the life cycle of a component, there are several good articles on Habré. What you are doing should be done via componentDidUpdate.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question