Reputation: 1073
I'm trying to understand why I can't seem to pass a parameter into a selector.
In essence: I have a logic that stores a number and a bool - the number is the parameter I want to select a material element by - I have a button that dispatches an action:
//on a jobcard - dispatches to the material logic slice, pushing the number into the redux state: materialforJobNumber;
<button className="materialViewer" onClick={() =>{dispatch(materialView(data.jobsessionkey))}}> MATERIAL</button>
which dispatches to the logic slice:
//logic slice
materialView:(state, action)=>{
console.log("what");
console.log("material view succesfully called", action);
const newState = {...state};
console.log(newState);
newState.materialforJobNumber = action.payload;
newState.showMaterial=true;
return newState
},
//the component that handles displaying the list of material for a job;
import {selectAttachedByJobKey} from "../MaterialCard/MaterialSlice";
const store= useStore();
const foundJN = store.getState().logic.materialforJobNumber;
const selectedJob=store.getState().jobs.find(x=>x.jobsessionkey==foundJN);
const materials = useSelector(selectAttachedByJobKey(foundJN));
const materialCards = materials.filter(x=>x.AttachedJobKey==foundJN).map((x,i)=><MaterialCard props={x} key ={i} />)
//material slice:
import { createSlice } from '@reduxjs/toolkit';
export const selectAttachedByJobKey = (state,action) =>{
console.log("selecting material by job key",action);
console.log(action?.payload);
console.log(state);
return state.material.filter(x=>x.AttachedJobkey===action?.payload);
}
I'm trying to get related material of a 'job' to show up on a click of a button. I'm using the createReducer function pattern, and I'm a bit lost on how to achieve this - is there a cleaner way for using a selector with a property?
Upvotes: 3
Views: 3912
Reputation: 10382
useSelector
takes a function with only state
as argument. if you want to pass other variables you could use a currying approach as:
export const selectAttachedByJobKey = (action) => (state) =>{
console.log("selecting material by job key",action);
console.log(action?.payload);
console.log(state);
return state.material.filter(x=>x.AttachedJobkey===action?.payload);
}
now when you do const materials = useSelector(selectAttachedByJobKey(foundJN));
you will be passing to useSelector
a function with foundJN
available.
Upvotes: 6