Búsqueda de sitios web

reactjs - No se puede encontrar el espacio de nombres 'GameContext'


Estoy tratando de usar el hook useContext en React con Typescript. Obtengo un error que dice No se puede encontrar el espacio de nombres 'GameContext'.

He usado esta misma sintaxis con .js normal, pero con Typescript parece que no funciona.

import { createContext, useState } from 'react';

export const GameContext = createContext();

export const GameProvider = (props) => {
  const [game, setGame] = useState({});

  return (
    <GameContext.Provider value={[game, setGame]}>
      {props.children}
    </GameContext.Provider>
  )
}

Respuesta #1

Ese mensaje de error en particular es extraño (una traza de pila ayudaría), pero puedo ver de inmediato que no has tipado correctamente tu contexto o proporcionado un valor inicial. El valor inicial es opcional en JS pero es obligatorio en TS.

import React, { createContext, useState, useContext, Dispatch, SetStateAction, PropsWithChildren } from 'react';

// replace this with your actual type
type Game = {}

// tuple with the same types as the useState tuple
type GameContextValue = [ Game, Dispatch<SetStateAction<Game>> ]

// set an initial value with a game and setGame that fulfill the expected type
export const GameContext = createContext<GameContextValue>([
    {}, 
    () => console.error("attempted to use GameContext outside of a Provider")
]);

// need to set a type for props which includes children
export const GameProvider = (props: PropsWithChildren<{}>) => {
  // need to declare the type for the state
  const [game, setGame] = useState<Game>({});

  return (
    <GameContext.Provider value={[game, setGame]}>
      {props.children}
    </GameContext.Provider>
  )
}

const Test = () => {
    // game and setGame get proper types
    const [game, setGame] = useContext(GameContext);
}

Enlace del parque