2

I'm new to Typescript and react and am getting this error, on default card

I am trying to setup use context and will use it with use state or use reducer but I am having trouble wrapping my head around initial setup for this

Error:
Argument of type '{ cartitem: { id: number; name: string; description: string; price: string; }; addCart: () => void; removeCart: () => void; }' is not assignable to parameter of type 'CartContextType'.
  Types of property 'cartitem' are incompatible.
    Type '{ id: number; name: string; description: string; price: string; }' is missing the following properties from type 'ICart[]': length, pop, push, concat, and 29 more.ts(2345)



import React, { createContext } from 'react';
export interface ICart {
    id: number;
    name: string;
    description: string;
    price: string;
  }

export type CartContextType = {
    cartitem: ICart[];
    addCart: (cart: ICart, totalAmount:number) => void;
    removeCart: (id: number) => void;
  };

  const defalutCart={cartitem:{
    id: 0,
    name: 'string',
    description: 'string',
    price: 'string'},
    addCart: () => {},
    removeCart: () => { }
  }

export const CartContext = createContext<CartContextType | null>(defalutCart);

1 Answer 1

1

Your variable defalutCart needs the property cartitem to be an array. With the correct spelling and changes, here is your updated code:

const defaultCart = {
  cartitem: [
    {
      id: 0,
      name: "string",
      description: "string",
      price: "string",
    },
  ],
  addCart: () => {},
  removeCart: () => {},
};

Do you see how the object is now wrapped in an array? Please mark this as correct if it solves your problem.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.