Guide on initializing a Redux toolkit state with an array of objects or local storage using TypeScript

Currently, I am attempting to set an initial state (items) to an array of objects or retrieve the same from localStorage. However, I am encountering the following error.

Type 'number' is not assignable to type '{ id: string; price: number; quantity: number; totalPrice: number; name: string; }[]'.ts(2322) cart.ts(4, 3): The expected type comes from property 'items' which is declared here on type 'SliceState'

type SliceState = {
  items: {
    id: string;
    price: number;
    quantity: number;
    totalPrice: number;
    name: string;
  }[];
  totalQuantity: number;
  totalPrice: number;
};

const initialState: SliceState = {
  items: [] | localStorage.getItem("cart"),
  totalQuantity: 0,
  totalPrice: 0,
};


const cartSlice = createSlice({
  name: "cart",
  initialState,
  reducers: {
    addItemToCart(state, action: PayloadAction<any>) {
      const newItem = action.payload;
      const existingItem = state.items.find((item) => item.id === newItem.id);
      state.totalQuantity++;
      if (!existingItem) {
        state.items.push({
          id: newItem.id,
          price: newItem.price,
          quantity: newItem.quantity,
          totalPrice: newItem.price * newItem.quantity,
          name: newItem.name,
        });
      } else {
        existingItem.quantity += action.payload.quantity;
        existingItem.totalPrice =
          existingItem.totalPrice + newItem.price * newItem.quantity;
      }
      localStorage.setItem("cart", JSON.stringify(state.items));
}
}

Is there a way to achieve what I'm attempting to do? I am also working with Next.js and I am aware that SSR can pose challenges with localStorage.

Answer №1

Your syntax is incorrect in this instance:

items: [] | localStorage.getItem("cart")

The correct syntax should be:

items: localStorage.getItem("cart") || []

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

What are the methods to manage rate limiting in Next.js 14?

I have recently started working with Next Js 14 and Mongo DB. While using Node Js, I learned about the Express Rate Limit package which allows for controlling the number of requests made by website users. If a user exceeds 200 requests in a span of 15 min ...

Angular modal not progressing past initial message due to Bootstrap integration issue

The modal functionality only seems to be working for the first message I send, as subsequent messages do not appear. My environment includes: Angular 17 Bootstrap 5.3 This is the TypeScript file snippet: import { Component } from '@angular/core&apos ...

The PHP function is returning an undefined value in JavaScript

I feel like there must be a simple solution to this problem that I just can't seem to find. Everything related to PHP search functions and queries is functioning properly, except for the fact that the data isn't displaying correctly in the text a ...

Input of data and salt must be provided

(node:35) UnhandledPromiseRejectionWarning: Error: data and salt arguments required. Can someone please assist me in resolving this error that I am encountering? const validatePassword = (password) => { return password.length > 4; }; app.post("/r ...

Is there a way to implement full-page scrolling in Vue?

Looking for a Vue equivalent of the fullpage.js library. Need a component that allows scrolling through elements similar to fullpage.js. ...

Setting up the JSON reply

When creating a schema using Joi and expecting a JSON response that matches the schema upon POSTing, an issue arises. The dilemma is having to include a parent element (in this case "data:") in the JSON response, although ideally the schema's attribut ...

Setting the "status" of a queue: A step-by-step guide

I created a function to add a job to the queue with the following code: async addJob(someParameters: SomeParameters): Promise<void> { await this.saveToDb(someParameters); try { await this.jobQueue.add('job', ...

Creating a generic that generates an object with a string and type

Is there a way to ensure that MinObj functions correctly in creating objects with the structure { 'name': string }? type MinObj<Key extends string, Type> = { [a: Key]: Type } type x = MinObj<'name', string> Link to Playgr ...

Is there a way to extract the visible text from an HTML TextNode without including the HTML tags?

My current challenge involves converting a DOM node and all of its children into plain text markup of a custom design. Utilizing node.childNodes allows me to retrieve a list of all content, which can then be recursively transformed into my desired string f ...

React: When an array state is controlling my components, why aren't they re-rendering?

I am facing an issue with my app where the className of buttons is not updating correctly when clicked. It seems that only active buttons trigger a re-render, while non-active ones do not. This behavior is confusing to me. Here's the code snippet for ...

Dealing with Redis session management in the event of a database disconnection

Having trouble with losing connection to Redis, which is used for sessions in my Express App. var RedisStore = require('connect-redis')(express); sessionStore = new RedisStore(config.db.redis.connection); sessionStore.client.on('error' ...

stop an html page from opening a new window

When using my HTML-based application, there are instances when it needs to open another URL within an iframe. However, a problem arises when the third-party URL within the iframe also opens a new window with the same content and URL. How can I prevent th ...

Firebase authentication encountered an error due to a network request failure

Utilizing firebase Hosting to host my website, I am encountering a persistent error when attempting to login using email/password. This is the JavaScript code that I am using: window.onload = () => initApp(); //Initialize screen function initApp(){ ...

Turning an Array of Objects into a typical JavaScript Object

Below are arrays of numbers: var stats = [ [0, 200,400], [100, 300,900],[220, 400,1000],[300, 500,1500],[400, 800,1700],[600, 1200,1800],[800, 1600,3000] ]; I am seeking guidance on how to transform it into the JavaScript object format shown below. ...

Unexpected Behavior: using setTimeout in a ReactJS class component leads to incorrect value retrieval

App Component: class App extends React.Component { constructor() { super(); this.state = { user: 'Dan', }; } render() { return ( <React.Fragment> ...

What is the best method for adding a JSON array with objects to an already existing table?

After incorporating Bootstrap into my HTML file, I designed a basic table. To populate this table with data from an external JSON file upon clicking a button, I utilized XMLHttpRequest and JSON.parse successfully. However, I encountered difficulties when t ...

JavaScript code to transform a string into a JSON array

I utilized s3 select to extract specific data for display on my frontend. I converted an array of bytes to a buffer and then to a string as shown below: let dataString = Buffer.concat(records).toString('utf8'); The resulting string looked like ...

Is there a way to transform Observable<Observable<Organization>[]> into Observable<Organization[]>?

I have implemented ngrx/store in my project. .map((p: Observable<Organization>[]) => { return new usersActions.GetOrganizationSuccess(p); }) The GetOrganizationSuccess action is designed to accept Organization[] as the payload. Is ...

What is the process for integrating material symbols into a Next.js project?

I'm currently using Next.js version 13.2 and I am looking to integrate the material-symbols into my project. My goal is to utilize it in the following manner: <span className="material-symbols-rounded">face</span> Upon further ...

Is it possible to use uglifyjs to merge multiple files into a single minified file?

I attempted to compress multiple javascript files into one using the uglifyjs tool, but encountered an issue. I ran $node uglifyjs.js to execute the file. Below is the content of the uglify.js file: var fs = require('fs'); var uglifyjs = re ...