简体   繁体   中英

React-TypeScript ConextAPI error while creating context

I am trying to replicate and learn from this package: https://github.com/AlexSegen/react-shopping-cart

I am using a React-Typescript project and I am facing issues while creating the ProductContext in the TypeScript way. I am trying the following code, but getting errors:

import React, { createContext, useState } from 'react';
import { dummyProducts } from '../constants/dummyProducts';

interface IProducts {
    id: number;
    name: string;
    price: number;
    photo: string;
    details: string;
}
export const ProductsContext = createContext<IProducts>({} as IProducts);

const ProductsContextProvider = ({children}) => { <--- Error1 Here

    const [products] = useState(dummyProducts);

    return ( 
        <ProductsContext.Provider value={products} >  <--- Error2 here
            { children }
        </ProductsContext.Provider>
     );
}
 
export default ProductsContextProvider;

These are the errors that I am getting:

//Error1:
var children: any
Binding element 'children' implicitly has an 'any' type.

//Error2:
(JSX attribute) React.ProviderProps<IProducts>.value: IProducts
Type '{ id: number; name: string; price: number; photo: string; details: string; }[]' is missing the following properties from type 'IProducts': id, name, price, photo, detailsts(2739)
index.d.ts(333, 9): The expected type comes from property 'value' which is declared here on type 'IntrinsicAttributes & ProviderProps<IProducts>'

I am not sure if this is the correct way of using this.

As the error states, you didn't typed props:

type Props = { children: React.ReactElement }
const ProductsContextProvider = ({children} : Props) => {...}

And your state doesn't match the provider value:

// Its a single product type
interface IProduct {
    id: number;
    name: string;
    price: number;
    photo: string;
    details: string;
}

export const ProductsContext = createContext<IProduct[]>([]);

// Guess its an array
const [products] = useState<IProduct[]>(dummyProducts);

// Products should be of type IProduct[]
<ProductsContext.Provider value={products}>

You need to type the props of the components,

interface ProductsContextProviderProps {
     children: ReactChildren
}

const ProductsContextProvider = ({children}: ProductsContextProvider) => 

    const [products] = useState(dummyProducts);

    return ( 
        <ProductsContext.Provider value={products}> 
            { children }
        </ProductsContext.Provider>
     );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM