Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to add type to react useReducer reducer function?

I have this useReducer function in pure react without type script now I would like to add types to it.

useReducer reducer function with pure react without types

export const cartReducer = (state, action) => {
  switch (action.type) {
    case "ADD_TO_CART":
      return { ...state, cart: [...state.cart, { ...action.payload, qty: 1 }] };
 
    default:
      return state;
  }
};

Here is what I have tried so far adding types to reducer function

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

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

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


export const cartReducer = (state:IState, action:Actions): IState =>{
    console.log('state', state)
    switch (action.type) {
        case "ADD_TO_CART":
            console.log('ADD_TO_CART')
            return {
                ...state,
                cart: [...state.cart, { ...action.payload, qty: 1}]
              };
    
        default:
            return state;
    }
}
  1. TS2322: Type '[any]' is not assignable to type '[]'.
    
 TS2698: Spread types may only be created from object types.

enter image description here

>Solution :

You have two problems:

The first one is you defined your cart type as [] which means that the only possible value for that is an empty list. If your list will consist of multiple objects, your type may become:

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

But then comes problem two, you are spreading a number which is incorrect, probably you incorrectly defined that interface as you say your JS code is working. If it’s correct, then instead of:

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

you should do

 cart: [...state.cart, { payload: action.payload, qty: 1}]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading