Anusha Ganti
Anusha Ganti

Reputation: 13

React + TS + hooks problem at action dispatch

Please tell me what im doing wrong in here:

I get the following error Type '{ wishList: any; addBookToWishList: (book: any) => void; }' is not assignable to type '{ wishList: never[]; }'. Object literal may only specify known properties, and 'addBookToWishList' does not exist in type '{ wishList: never[]; }'.ts(2322)

import React, {createContext, useReducer, useEffect} from "react";
import AppReducer from "./AppReducer";

//initial state
const initialState = {
    wishList: [],
}

//create context
export const GlobalContext = createContext(initialState);

//provider component

export const GlobalProvider = (props:any) => {
    const [state, dispatch] = useReducer(AppReducer, initialState);

    

// actions
const addBookToWishList = (book : any) => {
    dispatch({ type: "ADD_BOOK_TO_WISHLIST", payload: book })

    return(
        <GlobalContext.Provider 
          value={{
            wishList: state.wishList,
            addBookToWishList,
          }}
        >
          {props.children}
        </GlobalContext.Provider>
    )
}

Upvotes: 1

Views: 193

Answers (1)

Robert
Robert

Reputation: 2763

What a mess... first create type of your wish list item;

i gess book

  type Book = {
      title: string,
  }

 
  const initState = {
      wishList: new Array<Book>(),
  }

  const addBookToWishList = (book: Book) => {
    dispatch({ type: "ADD_BOOK_TO_WISHLIST", payload: book })

Upvotes: 1

Related Questions