Eliya
Eliya

Reputation: 40

How do I configure axios in react to retrieve data with an objects id from an api?

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>
      ) ;
} 

Upvotes: 1

Views: 2676

Answers (1)

Alan Z
Alan Z

Reputation: 912

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>

Upvotes: 1

Related Questions