Reputation: 237
Hello Everyone I am new to react-hook I have some doubts about the useEffect call method
1 . I have one warning issue react Hook useEffect has a missing dependency "get data". Either include it or remove the dependency array react-hooks/exhaustive-deps I fixed that issue by using this command line // eslint-disable-next-line react-hooks/exhaustive-deps, if I am doing like this correct or not if any issue occurs in future production server.
Thanks for Help
const [user,setUser]=useState([]);
const [post,setPost]=useState([]);
const UserList =()=>{
axios.get("https://jsonplaceholder.typicode.com/users")
.then((res)=>{
setUser(res.data)
})
}
const PostList =()=>{
axios.get("https://jsonplaceholder.typicode.com/post")
.then((res)=>{
setPost(res.data)
})
}
useEffect (()=>{
PostList();
UserList();
},[])
Upvotes: 1
Views: 2136
Reputation: 301
Memory leaks happens when you try to set a state after your component is unmounted and this often happens when you set your state in async/promise functions.
One solution that I have been using for a while is initiating a variable outside component and check that variable before updating your state.
let isMounted = true;
const YourComponent = () => {
const UserList = () => {
axios.get("https://jsonplaceholder.typicode.com/users")
.then((res)=>{
if(isMounted){
setUser(res.data)
}
})
}
useEffect(() => {
UserList();
return () => {
isMounted = false;
}
}, []}
}
Upvotes: 1
Reputation: 70
after fetch data, need cleanup function. UseEffect(callback, deps) allows you to easily cleanup side-effects. When the callback function returns a function, React will use that as a cleanup function
useEffect(() => {
let controller = new AbortController(); (async () => {
try {
//fetch
} catch (e) {
// Handle fetch error
}
})();
return () => controller?.abort(); }, []);
obviously this is one option how you can deal with it
Upvotes: 0
Reputation:
Your API calls are not asynchronous, so the state is not updated until the API call is complete, but the components are rendered onto the screen which depends on the values of the state. Make your API calls async.
Upvotes: 1