I have written a very simple sandbox to try to better understand useContext in Typescript. Im getting some strange errors but it still seems to work.
https://codesandbox.io/s/typescript-usereducer-nygts?file=/src/App.tsx
import { useEffect, useReducer, createContext, useContext } from "react";
import "./styles.css";
let AppContext = createContext(undefined);
type AppState = {
value: number;
};
type Action = {
type: string;
};
const initialState = {
value: 0
};
const reducer = (state: AppState, action: Action) => {
switch (action.type) {
case "INCREMENT":
state = { value: state.value + 1 };
return state;
default:
return state;
}
};
function Subscribe() {
const { state } = useContext(AppContext);
console.log("state", state);
return (
<>
<p>subscriber</p>
<p>state = {state.value}</p>
</>
);
}
export default function MyApp() {
let [state, dispatch] = useReducer(reducer, initialState);
useEffect(() => {
dispatch({ type: "INCREMENT" });
}, []);
console.log("TodoApp.state", state);
return (
<AppContext.Provider value={{ state }}>
<Subscribe />
</AppContext.Provider>
);
}
I have an error on AppContextProvider.value:
Type '{ state: AppState; }' is not assignable to type 'undefined'.ts(2322)
index.d.ts(335, 9): The expected type comes from property 'value' which is declared here on type 'IntrinsicAttributes & ProviderProps<undefined>'
and another on the useContext assignment: const { state } = useContext(AppContext);
Property 'state' does not exist on type 'undefined'.
I am clearly passing state to the subscriber and its updating so unsure why ts is complaining nor how to remedy it. Any advice is much appreciated.
Thanks