I'm trying to use Context API with Typescript and nothing is working properly, I'm very confused, I already checked a lot of articles on the internet and it still can't give me an understanding of this matter.
import { createContext, useState } from 'react';
export const SelectedContext = createContext<number>();
export const SelectedContextProvider = (props) => {
const [selectedId, setId] = useState(null);
const changeValue = (value:number | null) => {
setId(value);
}
return (
<SelectedContext.Provider value={{selectedId, changeValue}}>
{props.children}
</SelectedContext.Provider>
)
}
This is how I'm making my Context. I want it to have id: null as a default value but than when the user choose an option in Select I want to set is as number and make an API call. But right now I must specify default value for context and if I do than typescript shows me an error than type null can't be assigned to a number I want it to be in handleChange fuction.
And my second question is, how am I suppose to say what type my props will be right here if they're react children so it can be an empty array of array of React Nodes, I don't like to specify it as any because there's no use in using typescript in this situation.
<SearchContextProvider>
<CitySearchBar/>
<CitySelect/>
</SearchContextProvider>
Will someone be that kind and explain everything for me? I'm new to typescript and I don't know how to fix anmything :(
So I did like vuongvu suggested and now I'm getting
Type '{ selectedId: number | null; changeValue: (value: number | null) =>
void; }' is not assignable to type 'null'.ts(2322)
index.d.ts(335, 9): The expected type comes from property 'value' which is
declared here on type 'IntrinsicAttributes & ProviderProps<null>'
At my value attribute for context provider
So after major changes I'm getting only one error but it still shows up. It seems that now my provider expects only setter as a value, not both data and setter and I'm getting error like this:
Type '[MySelectedContextType,
Dispatch<SetStateAction<MySelectedContextType>>]' is not assignable to type
'Dispatch<SetStateAction<MySelectedContextType>>'.
Type '[MySelectedContextType,
Dispatch<SetStateAction<MySelectedContextType>>]' provides no match for the
signature '(value: SetStateAction<MySelectedContextType>): void'.ts(2322)
So the another problem I'm getting is when I try to consume this context I get this error:
TypeError: Object is not iterable (cannot read property
Symbol(Symbol.iterator))
And I'm getting it like u said:
const [selectedId, setSelectedId] = useSelectedContext();