tluanga hauhnar
tluanga hauhnar

Reputation: 91

Redux Toolkit -selectById

I tried to use selectbyId helper method of reduxtoolkit without a success can anyone help me with this

  1. Category Slice

    export const {
     selectAll:selectCatetories,selectById:selectCategoryById
     }=categoriesAdapter.getSelectors(state=>state.inventory.categories.categories)
    
  2. Category Component

    const category=useSelector((id)=>selectCategoryById(id))
    

I am sure there is something wrong with my implementation

Upvotes: 3

Views: 7596

Answers (2)

Safwat Fathi
Safwat Fathi

Reputation: 1005

You just need to pass the state to the useSelector function.

const category = useSelector((state)=>selectCategoryById(state, id))  

Upvotes: 2

Thomas
Thomas

Reputation: 61

To get your category with an Id, you will need to create a custom selector with reselect

import { createSelector } from '@reduxjs/toolkit';

const { selectById } = categoriesAdapter.getSelectors();

export const getCategoriesState = (rootState) => rootState.categories; // I am assuming you have a 'categories' reducer in your redux store.

export const selectCategoryEntity = (id) => {
   return createSelector(getCategoriesState, (state) => selectById(state, id));
}

Then, you will be able to use the selector hook in your React component:

const category = useSelector(selectCategoryEntity(id));

Upvotes: 3

Related Questions