Reputation:
I have a button that, when clicked, sends an object [ Dispatch(ADDS(myObject) ], but my [ Reducer ] does not return the object as the first ( index 0 ), it returns the first item ( empty ) because the ( InitialState ) it is set to ( empty ). How do I return the object as ( Index 0 ) ?
Console.log
My UI.js
import { createSlice } from '@reduxjs/toolkit';
export const slice = createSlice({
name: 'initial',
initialState : {
product: [],
},
reducers: {
ADDS(state, actions) {
return {
...state,
product: actions.payload,
}
}
}
});
export const { ADDS } = slice.actions;
export default slice.reducer;
Thanks
Upvotes: 0
Views: 706
Reputation: 697
here destructure your reducer response like this product: [...state.product, actions.payload]
import { createSlice } from '@reduxjs/toolkit';
export const slice = createSlice({
name: 'initial',
initialState : {
product: [],
},
reducers: {
ADDS(state, actions) {
return{
...state,
product: [...state.product, actions.payload]
}
}
}
});
export const { ADDS } = slice.actions;
export default slice.reducer;
Upvotes: 1
Reputation: 13077
You are currently replacing your array with your object in the reducer.
It’s not quite clear what you’re trying to achieve here, do you just want to add every new dispatched object to the array?
If so you need to something like this
product: state.push(actions.payload),
Upvotes: 0