Home > Net >  How to pass value to Context Provider in TypeScript?
How to pass value to Context Provider in TypeScript?

Time:10-24

I am trying to convert my react scripts to typescript and having issues defining the types:

export const inputListContext = createContext<null>(null)

import {MyEnum} from "../ts-api-script";


type checkBoxParams = {
    myEnum: any
    name: any
}


export const Options = () => {

const [greenVals, setGreenVals] = useState(Set<MyEnum>);
const [redVals, setRedVals] = useState(Set<MyEnum>);

const greenValue = {greenVals, setGreenVals};
const redValue = {redVals, setRedVals};


return (
  <inputListContext.Provider value={{greenValue, redValue}}>
    <Checkbox myEnum={FirmStatusEnum.Op} name={"Option 1"}</Checkbox>
 </inputListContext.Provider>

)
}

All I am trying to do is pass the red and green objects as values to my context provider. The issue is coming from typescript.

ERROR:
Type '{ greenValue: any; redValue: { redVals: { new (values?: readonly FirmStatusEnum[] | null | undefined): Set<MyEnum>; new (iterable?: Iterable<MyEnum> | null | undefined): Set<...>; readonly prototype: Set<...>; readonly [Symbol.species]: SetConstructor; }; setRedVals: React.Dispatch<...>; }; }' is not assignable to type 'null'

What are the steps I need to take to declare my types properly and rectify this?

CodePudding user response:

First, I think using Set<MyEnum> for useState initialization does not seem to be ok. So you can write the Options component like this:

function Options() {
    const [greenVals, setGreenVals] = useState(new Set<MyEnum>());
    const [redVals, setRedVals] = useState(new Set<MyEnum>());

    const greenValue = { greenVals, setGreenVals };
    const redValue = { redVals, setRedVals };

    return (
        <inputListContext.Provider
            value={{
                redValue,
                greenValue,
            }}
        >
            {/* whatever you want to pass */}
        </inputListContext.Provider>
    );
}

Then let's get to inputListContext. You should declare an interface outside of your Options component representing the inputListContext type, which based on what you mentioned in the question is something like this:

interface inputListContextType {
    greenValue: { greenVals: Set<MyEnum>, setGreenVals: Dispatch<SetStateAction<Set<MyEnum>>> };
    redValue: { redVals: Set<MyEnum>, setRedVals: Dispatch<SetStateAction<Set<MyEnum>>> };

}

And Next you create inputListContext not with null type and null initial value.

const inputListContext = createContext<inputListContextType>({
    greenValue: { greenVals: new Set<MyEnum>(), setGreenVals: () => { } },
    redValue: { redVals: new Set<MyEnum>(), setRedVals: () => { } },
});
  • Related