I have created one React app. For data fetching, I used axios. My app works fine as expected. But in my terminal, I am getting warning like this Line 34:6: React Hook useEffect has a missing dependency: 'props.match.params.id'. Either include it or remove the dependency array react-hooks/exhaustive-deps
. I don't want to use // eslint-disable-next-line react-hooks/exhaustive-deps
. Is there any alternative solution?
useEffect(() => {
axios
.get("http://localhost:5000/students/" + props.match.params.id)
.then(response => {
setState({
name: response.data.name,
birthday: response.data.birthday,
address: response.data.address,
zipcode: response.data.zipcode,
city: response.data.city,
phone: response.data.phone,
email: response.data.email
});
})
.catch(function(error) {
console.log(error);
});
}, []);
If you don't want to disable the eslint rule, you need to follow it, simply add the prop to your dependency array:
useEffect(() => {
axios
.get("http://localhost:5000/students/" + props.match.params.id)
.then(response => {
setState({
name: response.data.name,
birthday: response.data.birthday,
address: response.data.address,
zipcode: response.data.zipcode,
city: response.data.city,
phone: response.data.phone,
email: response.data.email
});
})
.catch(function(error) {
console.log(error);
});
}, [props.match.params.id]);
This means that if the id changes, your effect will be unmounted and called again, which seems to make sense, considering the match.params.id is used inside your effect.