Add paramater to redux useSelector hook

Viewed 861

I am learning Typescript and I have created a smalle app with

create-react-app my-app --template redux-typescript 

That has created a hook to type the useSelector

import { TypedUseSelectorHook,useSelector } from 'react-redux';
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector;

With the useAppSelector i want to select something from the store with a parameter

const favouriteList = useAppSelector((listKey) => selectFavouriteList(listKey));   

Without Typescript I thought I could solve this with currying.

const selectFavouriteList = (state: RootState) => (listKey: string) => {
            return state.favourites.lists[listKey]
        }

But TypesScript returns this error, it expects the store as parameter.

Argument of type 'DefaultRootState' is not assignable to parameter of type '{ favourites: favouriteListState; }'.
  Property 'favourites' is missing in type 'DefaultRootState' but required in type '{ favourites: favouriteListState; }'.ts(2345)
store.ts(8, 9): 'favourites' is declared here.

Does anyone has a suggestion how to sole this :-)?

1 Answers

You would do it this way:

const favouriteList = useAppSelector((state) => selectFavouriteList(state, listKey)); 

where listKey is a local varaible.

If you want to curry, do it the other way round:

const selectFavouriteList = (listKey: string) => (state: RootState) => {
            return state.favourites.lists[listKey]
}

const favouriteList = useAppSelector(selectFavouriteList(listKey)); 
Related