reactjsreact-nativematch

match.params.id not working in react router dom


I have installed the latest version of react-router-dom in my project. And it is saying match is undefined. However, it works fine when I use react-router-dom@5.2.0.

Can anybody tell me how should i change my code to use the match.params.id or what is the substitute method in the latest react-router-dom??

Attached is my code which is working fine in react router dom version@5.2.0.

import React from 'react';
import { useState, useEffect } from 'react';


function ItemDetail({match}) {
  const [item, setItem]= useState({});
  const [isLoading, setIsLoading] = useState(false);
  const [hasError, setHasError] = useState(false);
    useEffect(()=>{
        fetchItem();
        //console.log(match);
    // eslint-disable-next-line react-hooks/exhaustive-deps
    },[setItem]);
    
    const fetchItem= async ()=>{
      setIsLoading(true);
      setHasError(false);
      try {
        const fetchItem= await fetch(`https://fortnite-api.theapinetwork.com/item/get?id=${match.params.id}`
        );
        const item1 = await fetchItem.json();
        setItem(item1.data.item);
        console.log(item);
        console.log(item1);
        
      } catch (error) {
        setHasError(true);
      }
      setIsLoading(false);
        
    }    
  return (
    <div >
        <h1>{item.name}</h1>
    </div>
  );
}

export default ItemDetail;

Solution

  • You can try to use hooks: useParams, that returns an object with all variables inside your route

    const params = useParams();
    

    if the problem persists then it may be a problem with your component hierarchy or route definition