Rubayat26
Rubayat26

Reputation: 147

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 [email protected].

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 [email protected].

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;

Upvotes: 0

Views: 4441

Answers (4)

محمد رمضان
محمد رمضان

Reputation: 1

to resolve this problem you muss use useParams() and use useEffect() if you want conection with API
const [user,setUser]=useState('');
let param=useParams();
param.id!=null ? useEffect(()=>{
getUserOne(param.id)
.then((res)=>setUser(res.data))enter code here
.catch(()=>console.log('there is wrong'));

Upvotes: 0

Nazir Rizwan
Nazir Rizwan

Reputation: 11

First URL Route Path

<Route path='/book/:roomid' exact element={<Bookingscreen/>}/>

then import useParams match current URL

import { useParams } from 'react-router-dom';

const {roomid} = useParams();

/roomid in path so same name in useParams();

Upvotes: 1

Atul Yadav
Atul Yadav

Reputation: 61

First import { useParams } from 'react-router-dom';

add const {id} = useParams();

And instead of using (match.params.id) use only (id)

Hope this will work!

Upvotes: 1

Gabriel Alc&#226;ntara
Gabriel Alc&#226;ntara

Reputation: 626

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

Upvotes: 1

Related Questions