react-redux#batch TypeScript Examples

The following examples show how to use react-redux#batch. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: fetchCollectibles.ts    From multisig-react with MIT License 6 votes vote down vote up
fetchCollectibles = (safeAddress: string) => async (dispatch: Dispatch): Promise<void> => {
  try {
    const source = getConfiguredSource()
    const collectibles = await source.fetchCollectibles(safeAddress)

    batch(() => {
      dispatch(addNftAssets(collectibles.nftAssets))
      dispatch(addNftTokens(collectibles.nftTokens))
    })
  } catch (error) {
    console.log('Error fetching collectibles:', error)
  }
}
Example #2
Source File: useFetchTokens.tsx    From multisig-react with MIT License 6 votes vote down vote up
useFetchTokens = (safeAddress: string): void => {
  const dispatch = useDispatch<Dispatch>()
  const location = useLocation()

  useMemo(() => {
    if (COINS_LOCATION_REGEX.test(location.pathname)) {
      batch(() => {
        // fetch tokens there to get symbols for tokens in TXs list
        dispatch(fetchTokens())
        dispatch(fetchSelectedCurrency(safeAddress))
        dispatch(fetchSafeTokens(safeAddress))
      })
    }

    if (COLLECTIBLES_LOCATION_REGEX.test(location.pathname)) {
      batch(() => {
        dispatch(fetchCollectibles(safeAddress)).then(() => {
          dispatch(activateAssetsByBalance(safeAddress))
        })
      })
    }
  }, [dispatch, location.pathname, safeAddress])
}
Example #3
Source File: pendingTransactions.ts    From multisig-react with MIT License 6 votes vote down vote up
removeTxFromStore = (
  transaction: Transaction,
  safeAddress: string,
  dispatch: Dispatch,
  state: AppReduxState,
): void => {
  if (transaction.isCancellationTx) {
    const safeTransactions = safeTransactionsSelector(state)
    const transactions = safeTransactions.withMutations((txs) => {
      const txIndex = txs.findIndex(({ nonce }) => Number(nonce) === Number(transaction.nonce))
      txs[txIndex].set('status', TransactionStatus.AWAITING_YOUR_CONFIRMATION)
    })

    batch(() => {
      dispatch(addOrUpdateTransactions({ safeAddress, transactions }))
      dispatch(removeCancellationTransaction({ safeAddress, transaction }))
    })
  } else {
    dispatch(removeTransaction({ safeAddress, transaction }))
  }
}
Example #4
Source File: Covid19Data.ts    From covid19-trend-map with Apache License 2.0 6 votes vote down vote up
queryStateData = ({
    name, feature, FIPS
}:{
    name: string;
    feature?: QueryLocationFeature,
    FIPS: string
}) => (
    dispatch: StoreDispatch
    // getState: StoreGetState
): void => {
    if (name) {
        // const stateName = feature.attributes['STATE_NAME'];

        const queryLocation = {
            graphic: feature,
            locationName: name,
            FIPS
        };
        
        // should only result in one combined re-render, not two
        batch(()=>{
            dispatch(queryLocationUpdated(queryLocation));

            dispatch(
                fetchData({
                    stateName: name,
                })
            );
        })

        updateQueryInURLHashParams(FIPS);

    } else {
        dispatch(resetQueryData());
    }
}
Example #5
Source File: useSafeScheduledUpdates.tsx    From multisig-react with MIT License 5 votes vote down vote up
useSafeScheduledUpdates = (safeLoaded: boolean, safeAddress?: string): void => {
  const dispatch = useDispatch<any>()
  const timer = useRef<number>()
  const [isInitialLoad, setInitialLoad] = useState(true)

  useEffect(() => {
    // using this variable to prevent setting a timeout when the component is already unmounted or the effect
    // has to run again
    let mounted = true
    const fetchSafeData = async (address: string): Promise<void> => {
      await batch(async () => {
        const promises = [
          dispatch(fetchEtherBalance(address)),
          dispatch(fetchSafeTokens(address)),
          dispatch(fetchCollectibles(address)),
          dispatch(checkAndUpdateSafe(address)),
        ]
        // Don't make heavy request twice: transactions is loaded on useLoadSafe init
        if (!isInitialLoad) {
          promises.push(dispatch(fetchTransactions(address)))
        }
        await Promise.all(promises)
      })

      if (mounted) {
        timer.current = window.setTimeout(() => {
          setInitialLoad(false)
          fetchSafeData(address)
        }, TIMEOUT * 60)
      }
    }

    if (safeAddress && safeLoaded) {
      fetchSafeData(safeAddress)
    }

    return () => {
      mounted = false
      clearTimeout(timer.current)
    }
  }, [dispatch, safeAddress, safeLoaded, isInitialLoad])
}
Example #6
Source File: pendingTransactions.ts    From multisig-react with MIT License 5 votes vote down vote up
storeTx = async ({ transaction, safeAddress, dispatch, state }: StoreTxParams): Promise<void> => {
  if (transaction.isCancellationTx) {
    // `transaction` is the Cancellation tx
    // So we need to decide the `status` for the main transaction this `transaction` is cancelling
    let status: TransactionStatus = TransactionStatus.AWAITING_YOUR_CONFIRMATION
    // `cancelled`, will become true if its corresponding Cancellation tx was successfully executed
    let cancelled = false

    switch (transaction.status) {
      case TransactionStatus.SUCCESS:
        status = TransactionStatus.CANCELLED
        cancelled = true
        break
      case TransactionStatus.PENDING:
        status = TransactionStatus.PENDING
        break
      default:
        break
    }

    const safeTransactions = safeTransactionsSelector(state)

    const transactions = safeTransactions.withMutations((txs) => {
      const txIndex = txs.findIndex(({ nonce }) => Number(nonce) === Number(transaction.nonce))
      txs.update(txIndex, (tx) => tx.set('status', status).set('cancelled', cancelled))
    })

    batch(() => {
      dispatch(
        addOrUpdateCancellationTransactions({
          safeAddress,
          transactions: Map({ [`${transaction.nonce}`]: transaction }),
        }),
      )
      dispatch(addOrUpdateTransactions({ safeAddress, transactions }))
    })
  } else {
    dispatch(addOrUpdateTransactions({ safeAddress, transactions: List([transaction]) }))
  }
}
Example #7
Source File: fetchSafeTokens.ts    From multisig-react with MIT License 5 votes vote down vote up
fetchSafeTokens = (safeAddress: string) => async (
  dispatch: Dispatch,
  getState: () => AppReduxState,
): Promise<void> => {
  try {
    const state = getState()
    const safe = safeSelector(state)
    const currentTokens = tokensSelector(state)

    if (!safe) {
      return
    }

    const tokenCurrenciesBalances = await backOff(() => fetchTokenCurrenciesBalances(safeAddress))
    const currentEthBalance = safeEthBalanceSelector(state)
    const safeBalances = safeBalancesSelector(state)
    const alreadyActiveTokens = safeActiveTokensSelector(state)
    const blacklistedTokens = safeBlacklistedTokensSelector(state)
    const currencyValues = currencyValuesSelector(state)

    const { balances, currencyList, ethBalance, tokens } = tokenCurrenciesBalances.reduce<ExtractedData>(
      extractDataFromResult(currentTokens),
      {
        balances: Map(),
        currencyList: List(),
        ethBalance: '0',
        tokens: List(),
      },
    )

    // need to persist those already active tokens, despite its balances
    const activeTokens = alreadyActiveTokens.union(
      // active tokens by balance, excluding those already blacklisted and the `null` address
      balances.keySeq().toSet().subtract(blacklistedTokens),
    )

    const update = updateSafeValue(safeAddress)
    const updateActiveTokens = activeTokens.equals(alreadyActiveTokens) ? noFunc : update({ activeTokens })
    const updateBalances = balances.equals(safeBalances) ? noFunc : update({ balances })
    const updateEthBalance = ethBalance === currentEthBalance ? noFunc : update({ ethBalance })
    const storedCurrencyBalances = currencyValues?.get(safeAddress)?.get('currencyBalances')

    const updateCurrencies = currencyList.equals(storedCurrencyBalances)
      ? noFunc
      : setCurrencyBalances(safeAddress, currencyList)

    const updateTokens = tokens.size === 0 ? noFunc : addTokens(tokens)

    batch(() => {
      dispatch(updateActiveTokens)
      dispatch(updateBalances)
      dispatch(updateEthBalance)
      dispatch(updateCurrencies)
      dispatch(updateTokens)
    })
  } catch (err) {
    console.error('Error fetching active token list', err)
  }
}
Example #8
Source File: Covid19Data.ts    From covid19-trend-map with Apache License 2.0 5 votes vote down vote up
queryCountyData = ({
    FIPS, name, feature
}:{
    FIPS: string;
    name: string;
    feature?: QueryLocationFeature,
}) => (
    dispatch: StoreDispatch
    // getState: StoreGetState
): void => {

    if ( FIPS && name ) {

        const isNYCCounties = FIPSCodes4NYCCounties.indexOf(FIPS) > -1;

        const queryLocation:QueryLocation4Covid19TrendData = {
            graphic: feature,
            locationName: name,
            FIPS
        };

        // should only result in one combined re-render, not two
        batch(()=>{

            dispatch(queryLocationUpdated(queryLocation));

            dispatch(
                fetchData({
                    countyFIPS: FIPS,
                    isNYCCounties,
                })
            );
        })

        updateQueryInURLHashParams(FIPS);

    } else {
        dispatch(resetQueryData());
    }
}
Example #9
Source File: GridList.tsx    From covid19-trend-map with Apache License 2.0 4 votes vote down vote up
GridListContainer = () => {

    const sparklinesContainerRef = React.createRef<HTMLDivElement>();

    const dispatch = useDispatch();

    const {
        covid19LatestNumbers,
        covid19USCountiesData,
        covid19TrendData4USCountiesWithLatestNumbers,
        covid19TrendData4USStatesWithLatestNumbers
    } = useContext(AppContext);

    const activeTrend = useSelector(activeTrendSelector);

    const sortField = useSelector(gridListSortFieldSelector);

    const sortOrder = useSelector(gridListSortOrderSelector);

    const covid19CasesByTimeQueryLocation = useSelector(queryLocationSelector);

    const [sparklinesData4Counties, setSparklinesData4Counties] = useState<
        Covid19TrendDataWithLatestNumbers[]
    >([]);

    const sortData = (features:Covid19TrendDataWithLatestNumbers[]):Covid19TrendDataWithLatestNumbers[] => {
        let sortedFeatures = [
            ...features,
        ];

        // if(sortField === 'CaseFatalityRate' || sortField === 'CaseFatalityRate100Day'){
        //     sortedFeatures = sortedFeatures.filter(d=>d.attributes.Deaths > 0 && d.attributes.CaseFatalityRate100Day > 0)
        // }

        sortedFeatures.sort((a, b) => {
            return sortOrder === 'descending' 
                ? b.attributes[sortField] - a.attributes[sortField]
                : a.attributes[sortField] - b.attributes[sortField];
        });
        // console.log('sortedFeatures', sortedFeatures);

        return sortedFeatures;
    }

    const sortedData4Counties = useMemo(() => {

        return sortData([
            ...covid19TrendData4USCountiesWithLatestNumbers
        ]);

    }, [sortField, sortOrder]);

    
    const sortedData4States = useMemo(() => {

        return sortData([
            ...covid19TrendData4USStatesWithLatestNumbers
        ]);

    }, [sortField, sortOrder]);

    const loadSparklinesData = (endIndex?: number) => {
        console.log('calling loadSparklinesData', endIndex)
        if (!endIndex) {
            endIndex =
                sparklinesData4Counties.length + FeatureSetSize <= sortedData4Counties.length
                    ? sparklinesData4Counties.length + FeatureSetSize
                    : sparklinesData4Counties.length;
        }

        const featuresSet = sortedData4Counties.slice(0, endIndex);

        setSparklinesData4Counties(featuresSet);
    };

    const getFrame = useCallback(() => {
        const { frames } = covid19USCountiesData;

        const pathFrameByTrendName: {
            [key in Covid19TrendName]: PathFrame;
        } = {
            confirmed: frames.confirmed,
            death: frames.deaths,
            'new-cases': frames.newCases,
        };

        return pathFrameByTrendName[activeTrend];
    }, [activeTrend]);

    const onScrollHandler = () => {

        const conatinerDiv = sparklinesContainerRef.current;

        if (
            conatinerDiv.scrollHeight - conatinerDiv.scrollTop <=
            conatinerDiv.clientHeight
        ) {
            // console.log('hit to bottom');
            loadSparklinesData();
        }
    };

    useEffect(() => {
        const conatinerDiv = sparklinesContainerRef.current;
        conatinerDiv.scrollTo(0, 0);

        // reload sparklines data if sorted data is changed
        loadSparklinesData(FeatureSetSize);
    }, [sortedData4Counties]);

    return (
        <div
            ref={sparklinesContainerRef}
            className="fancy-scrollbar"
            style={{
                width: '100%',
                height: `calc(100% - ${HeaderHeight}px)`,
                paddingBottom: '60px',
                boxSizing: 'border-box',
                overflowY: 'auto',
            }}
            onScroll={onScrollHandler}
        >

            <GridList
                activeTrend={activeTrend}
                data={sortedData4States}
                frame={getFrame()}
                queryLocationFIPS={covid19CasesByTimeQueryLocation && covid19CasesByTimeQueryLocation.FIPS 
                    ? covid19CasesByTimeQueryLocation.FIPS 
                    : ''
                }
                paddingTop={5}
                title='STATE'
                // scrollToBottomHandler={loadSparklinesData}
                onHoverHandler={(FIPS, tooltipPosition)=>{
                    console.log(FIPS, tooltipPosition);

                    const stateFIPS = FIPS && tooltipPosition ? FIPS.substr(0,2) : null;
                    const stateAbbr = getStateAbbrev(stateFIPS);
                    const tooltipData = covid19LatestNumbers[FIPS];

                    batch(()=>{
                        dispatch(updateTooltipData(FIPS, tooltipData));
                        dispatch(tooltipPositionChanged(tooltipPosition));
                        dispatch(state2highlightInOverviewMapUpdated(stateAbbr));
                        dispatch(isOverviewMapVisibleToggled())
                    });

                }}
                onClickHandler={(FIPS)=>{
                    const data = covid19LatestNumbers[FIPS];

                    dispatch(queryStateData({
                        name: data.Name,
                        FIPS
                    }));
                }}
            />

            <GridList
                activeTrend={activeTrend}
                data={sparklinesData4Counties}
                frame={getFrame()}
                queryLocationFIPS={covid19CasesByTimeQueryLocation && covid19CasesByTimeQueryLocation.FIPS 
                    ? covid19CasesByTimeQueryLocation.FIPS 
                    : ''
                }
                // paddingTop={40}
                showTopBorder={true}
                title='COUNTY'
                // scrollToBottomHandler={loadSparklinesData}
                onHoverHandler={(FIPS, tooltipPosition)=>{
                    // console.log(FIPS, tooltipPosition);

                    const stateFIPS = FIPS && tooltipPosition ? FIPS.substr(0,2) : null;
                    const stateAbbr = getStateAbbrev(stateFIPS);
                    const tooltipData = covid19LatestNumbers[FIPS];

                    batch(()=>{
                        dispatch(updateTooltipData(FIPS, tooltipData));
                        dispatch(tooltipPositionChanged(tooltipPosition));
                        dispatch(state2highlightInOverviewMapUpdated(stateAbbr));
                        dispatch(isOverviewMapVisibleToggled())
                    });

                }}
                onClickHandler={(FIPS)=>{
                    const data = covid19LatestNumbers[FIPS];

                    dispatch(queryCountyData({
                        FIPS,
                        name: data.Name,
                    }));
                }}
            />
        </div>

    );
}