Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Hooks : fetch data inside useEffect warning

I am using react Hooks useEffect to fetch data from API in my component

props.getUserInfoAction() is an Action from redux dispatching user info 

Example

useEffect(() => {
        props.getUserInfoAction();
      }, []);

works great, I can get my data but i found that i have a warning show up in my console.

React Hook useEffect has a missing dependency: 'props'. Either include it or remove the dependency array. However, 'props' will change when any prop changes, so the preferred fix is to destructure the 'props' object outside of the useEffect call and refer to those specific props inside useEffect react-hooks/exhaustive-deps

I tried to pass the props in the array but by doing that i get an infinite loop of API call.

useEffect(() => {
            props.getUserInfoAction();
          }, [props]); 
like image 718
G.aziz Avatar asked Dec 22 '22 22:12

G.aziz


1 Answers

If props.getUserInfoAction() is an action you should instead of receiving already with a dispatch (from connect I assume) do this:

import {getuserInfoAction} from './actionCreators'
import {useDispatch} from 'react-redux'

const Comp = () =>{
    const dispatch = useDispatch()

    useEffect(() =>{
        dispatch(getUserInfoAction())
    },[dispatch])
}

Because even if you do this:

const {action} = props

Functions will always change between render calls.

like image 102
Dupocas Avatar answered Dec 26 '22 10:12

Dupocas