Version 1.9.3 of Redux Toolkit is encountering an error stating that the 'push' property is not found on the type 'WritableDraft<CartState>'

Currently delving into Redux Toolkit using TypeScript and facing a roadblock that seems deceptively simple. Unfortunately, my current knowledge isn't enough to unravel this puzzle and I'm in need of some guidance.

The issue arises with an error message stating 'Property 'push' does not exist on type 'WritableDraft'.' when executing the code snippet below:

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'
    }
  }
})

// Commented out since it wasn't used
// export const { addToCart, decrement, incrementByAmount } = cartSlice.actions
export const { addToCart } = cartSlice.actions

export default cartSlice.reducer

I recognize that the push() method fails because 'state' is not recognized as an array, yet a solution remains elusive considering the existing code structure. Any insights would be highly valued; thank you!

Answer №1

There is a missing field in your cart state called products:

export const shoppingCart = createSlice({
  name: 'shopping_cart',
  initialState,
  reducers: {
    addToCart: (state, action: PayloadAction<Product>) => {
      state.products.push(action.payload)
//          ~~~~~~~~
    }
  }
})

Playground

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Mixing Jest and Cypress in a TypeScript environment can lead to Assertion and JestMatchers issues

When utilizing [email protected] alongside Jest, we are encountering TypeScript errors related to Assertion and JestMatchers. What is the reason for these TypeScript errors when using Jest and [email protected] in the same project? ...

Elegantly intersect two types of functions in Typescript

Two function types are defined as follows: wrapPageElement?( args: WrapPageElementBrowserArgs<DataType, PageContext, LocationState>, options: PluginOptions ): React.ReactElement .. and .. wrapPageElement?( args: WrapPageElementNodeArgs<Data ...

Vue's Global mixins causing repetitive fires

In an effort to modify page titles, I have developed a mixin using document.title and global mixins. The contents of my mixin file (title.ts) are as follows: import { Vue, Component } from 'vue-property-decorator' function getTitle(vm: any): s ...

Is there a way to retrieve a specific type from a union-based type by using a generic function in Typescript?

When working with my API, I have noticed a consistent pattern where it returns either a specific type or a TypeScript type called BadResult, as shown below: type Result1 = CreatedPersonResult | BadResult; type Result2 = CreatedRoleResult | BadResult; To s ...

Trouble with references in Vue TypeScript when trying to access child component methods

I'm encountering an issue with calling a function in a child component while using typescript <notification ref="notification"></notification> <button @click="$refs.notification.show()"></button> Is there a ...

Using the typeof operator to test a Typescript array being passed as an object

I have a puzzling query about this particular code snippet. It goes like this: export function parseSomething(someList: string[]): string[] { someList.forEach((someField: string) => { console.log(typeof someField) }) Despite passing a s ...

Creating dynamic Kafka topic names within a NestJS microservice

Currently in Nestjs, I have integrated Kafka as my message broker and specified the topic name like so: @MessagePattern('topic-name') async getNewRequest(@Payload() message: any): Promise<void> { // my implementation logic } I am curious ...

Utilizing absolute path in Typescript: A comprehensive guide

I am currently working on a project written in Typescript running on NodeJS. Within the project, I have been using relative paths to import modules, but as the project grows, this approach is becoming messy. Therefore, I am looking to convert these relativ ...

Is it possible to ensure only one value is set as true in useReducer without manually setting the rest to false

I am seeking a more efficient method to ensure that only one value is set to true while setting the rest to false I came across this Python question and answer recommending an enum (I am not very familiar with that concept) Currently, I have the followin ...

best practices for choosing items from a dropdown menu using Angular

I have a dropdown list displaying existing tags/chips created by users in the past. However, I'm having an issue where when I select a tag from the dropdown list, it doesn't show up in my input field (similar to the Chart tag currently). I am abl ...

While attempting to index a nested object, TypeScript (error code 7053) may display a message stating that an element implicitly carries the 'any' type due to the inability to use an expression of type X to index type

I'm encountering an issue in TypeScript where I get the error (7053): Element implicitly has an 'any' type because expression of type X can't be used to index type Y when trying to index a nested object. TypeScript seems to struggle wit ...

Using a form template to bind radio buttons and automatically populate fields based on the selected radio button

My form has three radio buttons. The first one is selected by default. The second one should display an input field conditionally upon clicking it, and when the third option is selected, it should populate that input field with a certain value. div> ...

Execute a function when a button is pressed in a React application

Currently, I am dynamically generating some HTML and have a requirement for certain "events" to trigger an onclick function. The technology stack I am using for this project involves React and TypeScript. My initial approach is as follows: function add_ev ...

retrieve asynchronous data from the server using ngrx

How can I retrieve asynchronous data from the server? I am looking to save this data in a global store for future updates. I'm having trouble grasping the concept of asynchronous calls, such as in Redux. While I was able to understand it with simpl ...

Is there a way to bring in data from a .d.ts file into a .js file that shares its name?

I am in the process of writing JavaScript code and I want to ensure type safety using TypeScript with JSDoc. Since it's more convenient to define types in TypeScript, my intention was to place the type definitions in a .d.ts file alongside my .js fil ...

Mapping a list of records by a nested attribute using Typescript generic types

In my current project, I am implementing a unique custom type called "RecordsByType", which is currently undefined in the code snippet below. Within this snippet, I have various types that represent database records, each with its type defined within a ne ...

Issue with detecting window resize event in Angular 7 service

I have a unique service that utilizes a ReplaySubject variable for components, but strangely the WindowResize event isn't triggering. import { Injectable, HostListener } from '@angular/core'; import { ReplaySubject } from 'rxjs'; ...

What is the reason for not being able to call abstract protected methods from child classes?

Here is a simplified version of my project requirements: abstract class Parent { protected abstract method(): any; } class Child extends Parent { protected method(): any {} protected other() { let a: Parent = new Child() a.me ...

Is it not possible to call this authentication expression in a Typescript file when using Next JS?

I am currently developing a sign-in method for my Next.js application and I have been referring to the GitHub repository's recommended documentation. However, upon reaching the authentication folder step, I encountered an error regarding the sign-in ...

Tips for maintaining the original data type while passing arguments to subsequent functions?

Is there a way to preserve generic type information when using typeof with functions or classes? For instance, in the code snippet below, variables exampleNumber and exampleString are of type Example<unknown>. How can I make them have types Example& ...