i have this callback funtion inside useeffect i want to pass differnt props.id from parent js to this file so i get differnt datas the problem is const res = await axios.get("messages/get-all-messages/?receiver=" + props.id, config ); does not get recalled when i pass a new props.id from parent.js how can i call again this api when i pass a new props.id
function chat(e) {
e.preventDefault()
const config = {
headers: {
Authorization: `token ` + localStorage.getItem("token"),
},
};
const data = { receiver: props.id, message: inputField };
axios
.post("messages/send-message/", data, config)
.then((res) => {
getData();
})
.catch((error) => {
console.log(error);
});
}
const getData = useCallback(async () => {
const config = {
headers: {
Authorization: `token ` + localStorage.getItem("token"),
},
};
const res = await axios.get(
"messages/get-all-messages/?receiver=" + props.id,
config
);
undefined which will crash.
if (res.status === 200) {
if (mountedRef.current) {
setdata(res.data.);
}
}
}, []);
useEffect(() => {
if (mountedRef.current) {
getData();
}
return function cleanup() {
mountedRef.current = false;
};
}, [getData]);
useCallback(fn, deps)
useCallback will return a memoized version of the callback that only changes if one of the dependencies has changed. Therefore you should have been added props.id as dependencies to useCallback hooks
const getData = useCallback(async () => {
// do something
}, [props.id])
You can add props.id to the useEffect call, anything you pass as the an argument in the array will ensure that useEffect is called. Therefore anytime props.id updates the logic in the useEffect will execute.
"React compares the current value of dependency and the value on previous render. If they are not the same, effect is invoked."
Helpful Source:https://dev.to/nibble/what-is-useeffect-hook-and-how-do-you-use-it-1p9c
useEffect(() => {
if (mountedRef.current) {
getData();
}
return function cleanup() {
mountedRef.current = false;
};
}, [getData, props.id]);