1

I am able to access the object by passing its id in the const [id] = useState(2) and get the results hoped for. But want I want is when I navigate to http://127.0.0.1:8000/view/2 get the object without having to hard code the id in the useState. If I try to use const [id] = props.match.params.id i get an error that params is undefined. How do i get the id from the URL http://127.0.0.1:8000/view/9


//I have this route in App.js:
<Route exact path="view/:id" component={<ViewPage/>} />

//In ViewPage.js i have:

import React,{useEffect, useState} from 'react';
import  axios  from 'axios';
import ViewPageUI from './ViewPageUi';


function ViewPage(props) {

    const [tour, setTour] = useState({})
    const [id] = useState(2) // 2 is the id of an object


    useEffect(() => {
        axios.get(`http://127.0.0.1:8000/api/${id}`)
            .then(res => {
                console.log(res)
                setTour(res.data)
            })
            .catch(err => {
                console.log(err)
            })
    },[id]);

    return (
        <div>
            <h2>View Tour</h2>
            <ViewPageUI
                key={tour.id}
                name={tour.name}
                { *other code*} 
              />
           </div>
      ) ;
} 
Eliya
  • 40
  • 8

1 Answers1

1

You should use useParams hook inside the component.

import React,{useEffect, useState} from 'react';
import { useParams } from 'react-router-dom';
import  axios  from 'axios';
import ViewPageUI from './ViewPageUi';


function ViewPage(props) {

    const [tour, setTour] = useState({})
    const { id } = useParams() 


    useEffect(() => {
        if ( id ) {
            axios.get(`http://127.0.0.1:8000/api/${id}`)
                .then(res => {
                    console.log(res)
                    setTour(res.data)
                })
                .catch(err => {
                    console.log(err)
                })
        }
    }, [ id ]);

    return (
        <div>
            <h2>View Tour</h2>
            <ViewPageUI
                key={tour.id}
                name={tour.name}
            />
            {/* other code */}
        </div>
    );
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
Alan Z
  • 803
  • 1
  • 7
  • 13
  • Using let id= parsInt(useParams(). Id) did the magic also. – Eliya Dec 30 '21 at 23:29
  • @Eliya what if `id` is not a number type? Somebody could navigate by url and can use random string instead of number for that id. In that case, the react application will stop working. Something like `http://127.0.0.1:8000/view/random-slug`. – Alan Z Dec 31 '21 at 15:59