I have built a NodeJS server that reliably supports an API
http://localhost:5000/record/gopa
that returns a well formed JSON string
{"pid":
{
"ck":"F1965121910:265.522.5788.37",
"name":"gopa",
"cID":"MVOE9BW5ZZOC"
}
}
I have built a ReactJS client to received this JSON output and convert it into a string for subsequent processing as follows:
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();
window.alert(JSON.stringify(dbdata));
setData(dbdata);
//setData('fake data')
}
getData();
return;
},[dbdata]);
return (
<div>
<h3>Detail 52</h3>
<p>{dbdata}</p>
<p>{JSON.stringify(dbdata)}</p>
</div>
);
}
When this executes, I get NULL value in dbdata and a empty string when I convert the JSON output into a string.
I was initially under the impression that the ${params.id.toString()} was not being passed correctly, so for the time being I have hardcoded the parameter and the effect is the same.
I have tested this by placing an alert after dbdata is fetched and it shows null
To complete the testing, I have also placed a 'fake data' using the setData() functions and this fake data is correctly reflected in the final output.
So, I think, the problem is not with the setData() but with an empty string being returned.
I have been struggling with this for quite some time and I think that I have localised the problem. Would be very grateful if someone can help me sort this out.
First I think you inserted the wrong URL since you have a bracket at the end of it:
const response = await fetch(`http://localhost:5000/record/gopa}`);
//Instead of
const response = await fetch(`http://localhost:5000/record/gopa`);
I saw that you are awaiting twice your object:
const response = await fetch(`http://localhost:5000/record/gopa}`);
const dbdata = await response.json();
// How it should be:
const dbdata = response.json();
Can you please log us the content of the response, to understand if this is the issue or if the problem comes from another part of your code? I will edit the post if that's the case