I have a Provider
that provides a state variable and its corresponding setter through two contexts
.
const BookedBatchContext = createContext({})
const SetBookedBatchContext = createContext(null)
const initialState = {
id: null
}
The Provider
looks like this:
export const BookedBatchProvider = ({ children }: { children: any }) => {
const [bookedBatch, setBookedBatch] = useState(localState ||initialState)
return (
<SetBookedBatchContext.Provider value={setBookedBatch}>
<BookedBatchContext.Provider value={bookedBatch}>
{ children }
</BookedBatchContext.Provider>
</SetBookedBatchContext.Provider>
)
}
Through a custom hook I make the setBookedBatch
available to other components:
export const useBookedBatch = () => {
const bookedBatch = useContext(BookedBatchContext)
const setBookedBatch = useContext(SetBookedBatchContext)
return { bookedBatch, setBookedBatch }
}
When trying to use the setBookedBatch
function, I get following error in a given component:
setBookedBatch(selectedBatch)
The error:
TS2721: Cannot invoke an object which is possibly 'null'.
Since the setter of the useState
function is a function that I didn't create, I don't know how to initialise it when I create the context:
const SetBookedBatchContext = createContext(null)
So that TypeScript does not complain.
- How can I know the initial value of the setter function?
- How can I avoid that TS complains about the null value, if I am not providing any types?