0
votes

I have two components parent and child, I want to add dispatch event

Here are my interfaces

export interface IProduct {
        id: string;
        name: string;
        price: string;
        image: string;
        inStock: number;
        fastDelivery: boolean;
        ratings: number;
    }

Here are the parent component contents

import Products from './Products';
import { CartContext, IProduct } from "../context/Context";

const Contents: React.FC =()=> {
  const { state:{products}, dispatch } = useContext(CartContext);
  return (
          <div className="home-content">
                <Products products={products} cart={cart} />
       </div>
  )
}

export default Contents

Here is the child component

 import { CartContext, IProduct } from "../context/Context";
import { IState } from "../reducers/CartReducer";

const Products: React.FC <IState>= ({products}): JSX.Element => {

  return (
    <div className="products_container">
    {products.map((item) => {
      return (
        <Card  key={item.id}>
        <Card.Img variant="top" src={item.image} />
        <Card.Body>
          <Button 
          variant="primary" 
          onClick={() =>
            dispatch({
              type: "ADD_TO_CART",
              payload: item
            })
          }
          >
          </Button>

        </Card.Body>
      </Card>
      )
    })}
  </div>
  )
}

Here is my reducer function

import { IProduct } from "../context/Context";

export interface IState {
    products: IProduct[];
    cart: { payload: []}[];
}

export type Actions =
    | {type:"ADD_TO_CART", payload:[]}
    | {type:"REMOVE_FROM_CART", payload:[]}
    | {type: "CHANGE_CART_QTY", payload: []}


export const cartReducer = (state:IState, action:Actions): IState =>{
    console.log('state', state)
    switch (action.type) {
        case "ADD_TO_CART":
            return { 
                ...state,
                 cart: [...state.cart, {payload: action.payload}] 
                };
    
        default:
            return state;
    }
}

I am getting the following error, what am I doing wrong here?

enter image description here

1

1 Answers

1
votes
export type Actions =
    | {type:"ADD_TO_CART", payload:[]}
    | {type:"REMOVE_FROM_CART", payload:[]}
    | {type: "CHANGE_CART_QTY", payload: []}

The second line here is defining the payload type to be []. If IProduct is indeed the right type, then it should instead be:

| {type:"ADD_TO_CART", payload:IProduct}

You have some additional errors in the action handler that aren't showing up in your error messages yet:

cart: [...state.cart, {payload: action.payload}] 

should be:

cart: [...state.cart, action.payload]