Reputation: 1342
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.
Upvotes: 2
Views: 2665
Reputation: 5497
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 .
Upvotes: 3