简体   繁体   中英

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
}, [ ]);

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM