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]);

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x