Search code examples
reactjsreduxreact-redux

Redux with combined data


I'm working with web3 that includes connections to data fetching from smart contracts and other libraries. In the end I created 2 slices

  • 1 smart contract slices that fetches data from smart contracts like the circulating Supply
  • 1 slice for prices data

Then in many pages accross the app I use a metric called the "MarketCap" which is a computation between the price data :

marketCap = circulatingSupply * price 

In a Root component I do this :

...
    useEffect(() => {
        dispatch(initializeProviderContracts({ networkID: chainID, provider }));
        dispatch(getBlockchainData(provider));
        dispatch(getMarketPrices());
    }, [connected]);
...

What I do is this for each component :

Comp

const component = () => {

// get the states 
const price = useSelector(state => state.market.price);
const circulatingSupply = useSelector(state => state.contracts.token.circulatingSupply);

const marketCap = price * circulatingSupply; // Done several times 

} 

I couldn't find any tips about this in Redux, what is the best approach for it ? Do I need to create another slice like metrics and add an extra dispatcher ?


    useEffect(() => {
        dispatch(initializeProviderContracts({ networkID: chainID, provider }));
        dispatch(getBlockchainData(provider));
        dispatch(getMarketPrices());
        dispatch(computeMetrics()); // could be used to compute marketCap here
    }, [connected]);

Also is there a name for these type of redux operations ?

Thanks !


Solution

  • For derived values, use a selector.

    // somewhere
    
    export const selectMarketCap = state => state.market.price * state.contracts.token.circulatingSupply;
    
    // in your component
    
    const marketCap = useSelector(selectMarketCap);