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().