Search code examples
reduxreact-reduxreselect

redux : Select/get nested State by dynamic keys


Here my redux state , the state has dynamic nested object name

    const search = {
     client :
    { result: [],
      selected: null,
      isLoading: false,
      isSuccess: false,},
 [dynamicKey] :
    { result: [],
      selected: null,
      isLoading: false,
      isSuccess: false,},
 [dynamicKey2] :
    { result: [],
      selected: null,
      isLoading: false,
      isSuccess: false,}

    };

I'm trying to get nested object by dynamic key , here is my selector code :

import { createSelector } from "reselect";

export const searchState = (state) => state.search;

export const selectSearch = (keyRef) =>
  createSelector([searchState], (search) => search[keyRef]);

Solution

  • You forgot to ask the question but your code looks fine as it is. In the component you can use useMemo to not needlessly create the selector:

    //renamed the selector to create...
    export const createSelectSearch = (keyRef) =>
      createSelector([searchState], (search) => search[keyRef]);
    
    //compnent example
    const MyComponent = ({keyRef}) => {
      const selectSearch = React.useMemo(
        ()=>createSelector(keyRef),//create the selector when keyRef changes
        [keyRef]
      );
      const result = useSelector(selectSearch)
      return <jsx />
    }
    

    Some more information about this pattern can be found here