2

Using Reacts Context with Nextjs and TypeScript is showing a vague error wrapping context around the _app.tsx.

Event though I am passing in the values to the Context Provider it's giving me the error:

"Type '{ children: Element; }' is missing the following properties from type 'ContextProps': capturedPokemons, catchPokemon, releasePokemon"

Here is my _app.tsx

function MyApp({ Component, pageProps }: AppProps) {
  return (
    <CaughtProvider>
      <Component {...pageProps} />
    </CaughtProvider>
  );
}

Here is the Context:

type PokemonProps = {
  number: string;
  name: string;
  image: string;
};

type ContextProps = {
  capturedPokemons: PokemonProps[];
  catchPokemon: (newPokemon: PokemonProps[]) => void;
  releasePokemon: (id: string) => void;
};

const CaughtContext = createContext<ContextProps>({
  capturedPokemons: [],
  catchPokemon: () => undefined,
  releasePokemon: () => undefined,
});

export const useCaught = () => useContext(CaughtContext);

export const CaughtProvider: React.FC<ContextProps> = ({ children }) => {
  const [capturedPokemons, setCapturedPokemons] = useState<any>([]);

  const catchPokemon = (newPokemon: PokemonProps[]) => {
    if (capturedPokemons.length >= 6) {
      alert('You cannot carry any more Pokemon.');
      return;
    }

    const alreadyCaptured = capturedPokemons.some(
      (p: PokemonProps) => p.name === newPokemon[0].name
    );

    if (alreadyCaptured) {
      alert('you already have that pokemon');
      return;
    }

    if (window.confirm('Capture Pokemon')) {
      setCapturedPokemons([...capturedPokemons, ...newPokemon]);
    }
  };

  return (
    <CaughtContext.Provider
      value={{ catchPokemon, capturedPokemons, releasePokemon }}>
      {children}
    </CaughtContext.Provider>
  );
};

The app works fine as expected and as I'm aware this is how it's done in plain React/JS without TypeScript.

1 Answer 1

3

You need to have a separate type for the CaughtProvider

type CaughtProviderProps = {
children: React.ReactNode
}

and use it as

CaughtProvider: React.FC<CaughtProviderProps>

ContextProps is for your context value so its not right to use it for CaughtProvider . CaughtProvider is just a component which takes the children prop . So its better to have a separate type for it .

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.