boosted_duck
boosted_duck

Reputation: 508

useEffect missing dependency when using redux useDispatch

I wanna fetch my categories whenever my component is mounted using react hooks useEffect and not on every re-render. But i keep on getting this warning React Hook useEffect has a missing dependency:'dispatch'.

Here's my code:

const categories = useSelector(state => state.category.categories);
const dispatch = useDispatch();

useEffect(() => {
    console.log('effecting');
    const fetchCategories = async () => {
       console.log('fetching');
       try {
            const response = await axios.get('/api/v1/categories');
            dispatch(initCategory(response.data.data.categories));
       } catch (e) {
           console.log(e);
       }
    }

    fetchCategories();
}, []);

Upvotes: 11

Views: 7936

Answers (3)

César Riva
César Riva

Reputation: 221

You can safely add the dispatch function to the useEffect dependency array. If you look the react-redux documentation, specially the hooks section, they mention this "issue".

The dispatch function reference will be stable as long as the same store instance is being passed to the . Normally, that store instance never changes in an application.

However, the React hooks lint rules do not know that dispatch should be stable, and will warn that the dispatch variable should be added to dependency arrays for useEffect and useCallback. The simplest solution is to do just that:

export const Todos() = () => {
const dispatch = useDispatch();

useEffect(() => {
    dispatch(fetchTodos())
  // Safe to add dispatch to the dependencies array
  }, [dispatch])

}

Upvotes: 22

Eugene
Eugene

Reputation: 1

It might be a problem with ignored promise.

fetchCategories() returns a promise.

You can try

useEffect(() => {
    const fetchCategories = async () => {
       try {
            const response = await axios.get('/api/v1/categories');
            await dispatch(initCategory(response.data.data.categories));
       } catch (e) {
           console.log(e);
       }
    }

    fetchCategories().then(res => (console.log(res());
}, []);

Upvotes: 0

automasean
automasean

Reputation: 421

Add dispatch to your dependency array (which is currently empty).

useEffect(() => {
    console.log('effecting');
    const fetchCategories = async () => {
       console.log('fetching');
       try {
            const response = await axios.get('/api/v1/categories');
            dispatch(initCategory(response.data.data.categories));
       } catch (e) {
           console.log(e);
       }
    }

    fetchCategories();
}, [dispatch]);

Upvotes: 5

Related Questions