Reputation:
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.
Upvotes: 0
Views: 177
Reputation: 171
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>
);
}
Upvotes: 0
Reputation: 53874
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}>
Upvotes: 2