I was creating an online shopping website and tried to use React Typescript for that project, but when I tried to work with Contexts I couldn't fix this problem when I try to export my state in the Provider value
thanks for helping
ERROR
Type '{ products: IProductItem[] | undefined; setProducts: React.Dispatch<React.SetStateAction<IProductItem[] | undefined>>; }' is not assignable to type 'IProductContext'. Object literal may only specify known properties, and 'products' does not exist in type '[IProductItem[], Dispatch<SetStateAction<IProductItem[]>>]'.ts(2322) index.d.ts(332, 9): The expected type comes from property 'value' which is declared here on type 'IntrinsicAttributes & ProviderProps'
Context Code
import * as React from 'react';
import { useQuery } from "react-query";
type IProductContext = [IProductItem[], React.Dispatch<React.SetStateAction<IProductItem[]>>];
export const ProductContext = React.createContext<IProductContext>([[], () => null]);
const ProductProvider: React.FC<{}> = ({children}: { children?: React.ReactNode }) => {
    //fetching products data from a public API
    const getProducts = async (): Promise<IProductItem[]> => 
    await (await fetch("https://fakestoreapi.com/products")).json();
    //Retrieve the data and status using UseQuery
    const {data, isLoading, error} = useQuery<IProductItem[]>('products', getProducts);
    const [products, setProducts] = React.useState<IProductItem[] | undefined>();
    if(!error){
        setProducts(data)
    }
    
    return (
        <ProductContext.Provider value={{products, setProducts}}>
            {children}
        </ProductContext.Provider>
    );
};
export default ProductProvider;
export function useProducts(){
    const context = React.useContext(ProductContext);
    if(!context) throw new Error('useProducts must be inside a ProductProvider.');
    return context;
}
Types:
interface IProductItem{
    id: number
    title: string
    description: string;
    category: string;
    image: string;
    price: number;
    quantity: number;
}
type ProductType = {
    items: IProductItem[]
    saveItem: (item: ICartItem) => void
    updateItem: (id: number) => void
    removeItem: (id: number) => void
} | undefined;
In my case the issue was caused by other error which preceded this one. Look into the terminal for other errors preceding this one. By fixing the preceding error, this issue disappeared.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With