Reputation: 558
I'm trying to trigger the extra reducers, everytime when i dispatch the fillForm action. but the code isn't working. Any help ?
export const userSelectSlice = createSlice({
name: "userSelect",
initialState: {
name: localStoreData?.name || "",
salary: localStoreData?.salary || "",
job: localStoreData?.job || "",
location: localStoreData?.location || "",
eligibility: localStoreData?.eligibility || "",
},
reducers: {
fillForm: (state, action) => {
state.name = action.payload.name;
state.salary = action.payload.salary;
state.job = action.payload.job;
state.location = action.payload.location;
localStorage.setItem(
"userSelect",
JSON.stringify({
name: action.payload.name,
salary: action.payload.salary,
job: action.payload.job,
location: action.payload.location,
})
);
},
},
extraReducers: (builder) => {
builder.addCase(createAction('fillForm'), (state, action) => {
// extra reducer code goes here
console.log('sdcjknsdcjnsdjhcbsdjhb')
state.eligibility = 'sdckjsdcjnsdjcbdshjcb'
});
},
});
I tried several methods but wheren't of any help
Upvotes: 0
Views: 699
Reputation: 2545
As described in the documentatin:
reducers specified with extraReducers are meant to reference "external" actions
If two fields from reducers and extraReducers happen to end up with the same action type string, the function from reducers will be used to handle that action type.
This is the case in example you have provided. You can not have the same action handled twice in the same slice. ExtraReducers
is meant to allow you respond to other action types besides the types the slice has generated. So you can either
state.eligibility = 'sdckjsdcjnsdjcbdshjcb'
to existing reducerexport const userSelectSlice = createSlice({
name: "userSelect",
initialState: {
//...
},
reducers: {
fillForm: (state, action) => {
// ... do your stuff
console.log('fillForm slice reducer')
state.eligibility = 'sdckjsdcjnsdjcbdshjcb' // add code from extra reducers
},
},
});
export const someOtherSlice = createSlice({
name: 'otherSlice',
initialState: {
//...
},
reducers: {
// No fillForm action here
},
extraReducers: (builder) => {
builder.addCase(createAction('fillForm'), (state, action) => {
// extra reducer code goes here
// eslint-disable-next-line no-console
console.log('fillForm extraReducers')
})
}
})
export const fillFormExtra = createAction('fillForm')
export const userSelectSlice = createSlice({
name: 'userSelect',
initialState: {
eligibility: ''
},
reducers: {
fillForm: (state, action) => {
// eslint-disable-next-line no-console
console.log('fillForm slice reducer')
}
},
extraReducers: (builder) => {
builder.addCase(createAction('fillForm'), (state, action) => {
// extra reducer code goes here
// eslint-disable-next-line no-console
console.log('fillForm extraReducers')
state.eligibility = 'sdckjsdcjnsdjcbdshjcb'
})
}
})
and dispatch them separately
dispatch(userSelectSlice.actions.fillForm({}))
dispatch(fillFormExtra())
Upvotes: 1