skip to Main Content

I am new in React-Native, I am facing one issue in my app and not able to resolved that yet. All thing is working but first time API being calling two time unnecessary.

Here is my useEffect method :-

useEffect(() => {
    if (transactions.length === 0) {
      setIsAPICall(true);
    }
    getTransactions().then((response: any) => {
      dispatch(actionTransitionsBadge(0));
      setTransactions(response);
      setIsAPICall(false);
    });
  }, [user, onChainBalance]);

In this method I have to get transaction list when component first time open. After that I have to refresh this list when user and onChainBalance get updated. The thing is working but when I am loading this component first time then the api is calling multiple time.

What I can do to manage this flow that once component load then api call once after then when my two state changed the api call again.

2

Answers


  1. Put your getTransactions in the useCallback, like this:

      const fetchData=useCallback(
         () => {
         getTransactions().then((response: any) => {
          dispatch(actionTransitionsBadge(0));
          setTransactions(response);
          setIsAPICall(false);
        });
         },
         [],
        )
    

    Then call fetchData in the useEffect

    Login or Signup to reply.
  2. Here is some Details where you can useEffect .

    1. useEffect(() => {},)

    2. useEffect(() => {},[])

    3. useEffect(() => {},[dependency_array])

    Here I am explaining them one by one

    The first would call on every render 
    
    The Second would call two time 
    
    the third would call two times and when the dependency array changes
    

    Here is your use Case

    useEffect(() => {
        if(user !== null &&  user !== undefined && transactions.length === 0){
            getTransactions().then((response: any) => {
             dispatch(actionTransitionsBadge(0));
             setTransactions(response);
             setIsAPICall(false);
           });
        }
      }, [user, onChainBalance]);
    

    but Still this is not a good method. you should use react-query or redux-toolkit-query

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search