Fran M
Fran M

Reputation: 249

Infinite loop useEffect with useSelector

// get state
const { inscriptions } = useSelector( state => state.user );

// flag
const instances = Object.keys(inscriptions).length;

// dispatch
const dispatch = useDispatch();

const getInscriptions = () => dispatch( getInscriptionsAction() );

useEffect( () => {
    // call api only if empty
    if(instances === 0) {
        const queryToAPI = async () => {
            getInscriptions();
        }
        
        queryToAPI();
    }
    
    // eslint-disable-next-line react-hooks/exhaustive-deps
}, [ instances, inscriptions ]);

My problem is, whenever i call the API inside de useEffect that forces a store update, which makes the component to re-render and thus initiating the infinite loop. I can't either put something like if(isntances === 0) return null; or so below useEffect becouse my inscriptions array CAN be empty i tried adding all kind of flags but it keeps infinite looping. Any ideas?

==================EDIT================================ Okay now I've implemented some suggestions, but the problem still remains, the infinite loop stills.

// get state
const { inscriptions } = useSelector( state => state.user );

// flag
const instances = Object.keys(inscriptions).length;

// dispatch
const dispatch = useDispatch();

// const getInscriptions = () => dispatch( getInscriptionsAction() );

const getInscriptions = useCallback(
    () => dispatch( getInscriptionsAction() ),
    [ dispatch, getInscriptionsAction ]
);

useEffect( () => {
    // call api only if empty
    if(instances === 0) {
        // const queryToAPI = async () => {
            getInscriptions();
        // }
        
        // queryToAPI();
    }
    
    // eslint-disable-next-line react-hooks/exhaustive-deps
}, [ ]);

Upvotes: 5

Views: 4922

Answers (1)

Fran M
Fran M

Reputation: 249

Okay, I figure it out, one of my types in the Reducer rested de inscriptions to and empty array, so it was re-rendering infinitely.

Upvotes: 1

Related Questions