1

I am not being able to assign the state and setState to the value parameter of ContextProvider

Code:-

import React, { useState, createContext } from 'react';
import { makeStyles } from '@material-ui/core';
import ProductHeader from './components/productHeader';
import ProductTable from './components/productTable';

const styles = makeStyles((theme) => ({
    root: {
        height: '92.7%',
        position: 'fixed',
        width: '85%',
        bottom: '0',
        right: '0',
        border: `1px solid  ${theme.palette.success.light} `,
        overflow: 'hidden',
    },
}));
// use State + use Context

const ProductContext = createContext([]);

const ProductPortion: React.FC = () => {
    const classes = styles();
    const [products, setProducts] = React.useState([]);
    return (
        <div className={classes.root}>
            <ProductContext.Provider value={[setProducts, products]}>
                <ProductHeader />
                <ProductTable />
            </ProductContext.Provider>
        </div>
    );
};

export default ProductPortion;

The Exact Error :-

TypeScript error in C:/Users/dell/Desktop/Web current Projects/bigosoft/bigosoft/POS-Retail-Frontend/Retail-POS-Frontend/src/components/Management/components/productPortion/index.tsx(26,46):
Type 'Dispatch<SetStateAction<never[]>>' is not assignable to type 'never'.  TS2322

    24 |     return (
    25 |         <div className={classes.root}>
  > 26 |             <ProductContext.Provider value={[setProducts, products]}>
       |                                              ^
    27 |                 <ProductHeader />
    28 |                 <ProductTable />
    29 |             </ProductContext.Provider>

I want to pass the state and its setter to the children using the ContextProvider but I am getting the TypeScript error.

skyboyer
  • 22,209
  • 7
  • 57
  • 64
Abdullah Ch
  • 1,678
  • 1
  • 13
  • 31

1 Answers1

0

I think the problem is in

const ProductContext = createContext([])

See next example:

const foo=<T,>(arg:T)=>arg
foo([]) // never[]

But if you provide explicit type , it will be resolved as you expect:

foo<number[]>([]) // number[]

In your case, I believe, you should write smth like that:

const ProductContext = createContext<Products[]>([])

I assume you know your Products type