0

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

1 Answer 1

2

You didn't specify any context type. You can do something like this:

type AppContextType = {
   state: AppState
}
const AppContext = createContext<AppContextType|null>(null);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.