Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

154
Views
¿Cómo configuro axios en reaccionar para recuperar datos con una identificación de objetos de una API?

Puedo acceder al objeto pasando su id en const [id] = useState(2) y obtengo los resultados esperados. Pero lo que quiero es cuando navego a http://127.0.0.1:8000/view/2 obtengo el objeto sin tener que codificar la identificación en useState. Si trato de usar const [id] = props.match.params.id, obtengo un error que indica que los parámetros no están definidos. ¿Cómo obtengo la identificación de la 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> ) ; }
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Debe usar el gancho useParams dentro del componente.

 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>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!