I am trying to implement Contexts in my React project. Every time I have tried implementing this Context, I get the same error:
Property 'state' does not exist on type '{ count: number; currentColor: string; }'.
> 40 | let { state, dispatch } = React.useContext(ContextOne);
| ^
Context Provider code:
import * as React from "react";
let ContextOne = React.createContext(initialState);
let initialState = {
count: 10,
currentColor: "#bada55"
};
let reducer = (state, action) => {
switch (action.type) {
case "reset":
return initialState;
case "increment":
return { ...state, count: state.count + 1 };
case "decrement":
return { ...state, count: state.count - 1 };
case "set-color":
return { ...state, currentColor: action.payload };
}
};
function ContextOneProvider(props) {
let [state, dispatch] = React.useReducer(reducer, initialState);
let value = { state, dispatch };
return (
<ContextOne.Provider value={value}>{props.children}</ContextOne.Provider>
);
}
let ContextOneConsumer = ContextOne.Consumer;
export { ContextOne, ContextOneProvider, ContextOneConsumer };
I have tried numerous online example Context Providers, but every time useContext() is called, the same error appears. What needs to be modified to get the Context working?
------------------------------------------Edit------------------------------------------
Thanks to soywood, here is the working Context Provider code:
import * as React from "react";
type State = {
count: number
currentColor: string
}
const initialState: State = {
count: 10,
currentColor: "#bada55",
};
type Context = {
state: State
dispatch: React.Dispatch<Action>
}
type Action = {
type: string,
payload: string
}
const ContextOne = React.createContext<Context>({
state: initialState,
dispatch: () => {},
});
// You need to define the type Action
const reducer: React.Reducer<State, Action> = (state, action) => {
switch (action.type) {
case "reset":
return initialState;
case "increment":
return { ...state, count: state.count + 1 };
case "decrement":
return { ...state, count: state.count - 1 };
case "set-color":
return { ...state, currentColor: action.payload };
}
};
function ContextOneProvider(props) {
const [state, dispatch] = React.useReducer(reducer, initialState);
const value: Context = { state, dispatch };
return (
<ContextOne.Provider value={value}>{props.children} </ContextOne.Provider>
);
}
let ContextOneConsumer = ContextOne.Consumer;
export { ContextOne, ContextOneProvider, ContextOneConsumer };