Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

219
Visualizações
fetch() URL data with Javascript React and display as string

I have an api that is called like this :

http://localhost:5000/record/gopa

and it returns the data in this JSON format

{"pid":{
  "ck":"F1965121910:265.522.5788.37",
  "name":"gopa",
  "cID":"MVOE9BW5ZZOC"}
}

I want to call this from a React function Details2() that is called from a router like this:

import Details2 from "./components/Details2";
const App = () => {
 return (
   <div>
     <Navbar />
     <Routes>
       <Route exact path="/" element={<RecordList />} />
       <Route path="/singlerecord/:id" element={<RecordList1 />} />
       <Route path="/details2/:id" element={<Details2 />} />
     </Routes>
   </div>
 );
};

the parameter :id needs to be passed to the function Details2()
This function is located in file /components/Details2.js and is being called correctly.
I have stripped down the Details2.js file to the bare essentials and it contains

import React from "react";
import { useParams, useNavigate } from "react-router";

 
export default function Details2() {
 const params = useParams();
  
 let z = fetch(`http://localhost:5000/record/${params.id.toString()}`).then((response) => {
      return response.json();
    })
 let cname = z.pid.name
 return (
   <div>
     <h3>Details2</h3>
     {params.id.toString()}
     
   </div>
 );
}

I am trying to access the contents of the data that has been returned by the call for onward processing but I am unable to access it in any variable,like cname, that is shown here. No output is available, not even the header.
If I remove the assignment, the program works correctly, displays the HTML that is being returned including the value of params.id.toString() that is being correctly passed from the router.
My simple ask is to be able to access the individual values of the various keys that are being returned from the API. Please help me with the code that is required.
I have seen this article where they do something similar. However in this case they are using a class but I could not find a way to pass parameters into a class, as I am doing in the case of the function Details2().

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Here is what finally worked well :-)

import React, { useEffect, useState } from "react";
import { useParams } from "react-router";
 
export default function Detail52() {
 const params = useParams();
 const [dbdata, setData] = useState('empty52');
 
 useEffect(() => {
   async function getData() {
   const response = await fetch(`http://localhost:5000/record/${params.id.toString()}`);
   //const response = await fetch(`http://localhost:5000/record/gopa`);
 
     if (!response.ok) {
       const message = `An error occurred: ${response.statusText}`;
       window.alert(message);
       return;
     }
     
     const dbdata = await response.json();
     //dbdata = response.json();
     //window.alert(JSON.stringify(dbdata));
     setData(dbdata);
     //setData('fake data')
   }
   getData();
   return;
 },[dbdata]);
 
 return (
   <div>
     <h3>Detail Information</h3>     
       
       <p>{JSON.stringify(dbdata)}</p>
   </div>
 );
 
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda