Trying out ReduxToolkit with TypeScript and I'm stumped on something that I suspect is really simple / obvious. However, I don't know enough to figure it out and need some guidance.
Basically I get a Property 'push' does not exist on type 'WritableDraft'. error in the following code:
import { createSlice, PayloadAction } from '@reduxjs/toolkit'
import { Product } from '../pages/Product/Types'
export interface CartState {
products: Product[]
}
const initialState: CartState = {
products: []
}
export const cartSlice = createSlice({
name: 'cart',
initialState,
reducers: {
addToCart: (state, action: PayloadAction<Product>) => {
state.push(action.payload) <=== ERROR HERE, WITH 'push'
}
}
})
// Action creators are generated for each case reducer function
// export const { addToCart, decrement, incrementByAmount } = cartSlice.actions
export const { addToCart } = cartSlice.actions
export default cartSlice.reducer
I understand that push() isn't working because state isn't considered an array, but I don't see how to fix that, given what code is already here. Any help is appreciated; thanks!
Your cart state has a products
field that you are missing:
export const cartSlice = createSlice({
name: 'cart',
initialState,
reducers: {
addToCart: (state, action: PayloadAction<Product>) => {
state.products.push(action.payload)
// ~~~~~~~~
}
}
})