How to refact useRouteMatch according to the react-router-dom update to v6

Viewed 139

Hope u can help me to solve this problem! I'm a newcomer asking here so forgive me if I write something wrong.

Well, I've received a test for a job application and the purpose lookalike an old project of mine, it's a Pokedex basically, and I'm refactoring it in a new repository (I wanna use the packages at the latest version). It's been a long time since I've done the original one, and I was studying some other things so I wasn't focused on the react-router-dom updates and apparently useRouteMatch was deprecated. I've searched a lot about how to convert my old code according to the new hooks, but nothing showed up. So here is the code, made in React using Typescript:

interface PokemonParams {
  pokemon: string;
}

interface Pokemon {
  id: number;
  name: string;
  description: string;
  height: number;
  weight: number;
  base_experience: number;
  types: Array<Type>;
}

interface Type {
  type: {name: string;};
}

const Pokemon: React.FC = () => {
  const [pokemon, setPokemon] = useState<Pokemon | null>(null);
  const { params } = useRouteMatch<PokemonParams>();

  const loadPokemon = async () => {
    const pokemon = await getPokemon(params.pokemon);
    setPokemon(pokemon);
  }

  useEffect(() => {
    loadPokemon();
  }, [params.pokemon]);
1 Answers

The useRouteMatch hook was deprecated and not carried forward into react-router-dom@6. There is a useMatch hook that I feel is the spiritual successor, but it's not a direct replacement. From the code it appears you are only trying to access the route path params, and for this you would use the useParams hook. Coincidentally this is the same hook you probably should have also been using in RRDv5, see useParams v5.

Example:

const Pokemon: React.FC = () => {
  const [pokemon, setPokemon] = useState<Pokemon | null>(null);
  const { pokemon } = useParams<PokemonParams>();

  useEffect(() => {
    const loadPokemon = async () => {
      const fetchedPokemon = await getPokemon(pokemon);
      setPokemon(fetchedPokemon);
    }

    loadPokemon();
  }, [pokemon]);
Related