Why am I unable map JSON object data in Next.js? - json

I am trying to display some JSON data that I receive from my backend. I first have a useEffect which retrieves the JSON data:
const [backendData, setBackendData] = useState(null)
useEffect(() => {
const fetchUserData = async () => {
const response = await fetch('http://localhost:5000/api/userData/')
const json = await response.json()
// check if response is ok
if (response.ok) (
setBackendData(json)
)
}
fetchUserData()
console.log(backendData, 'hi')
}, [])
And then in my JSX code I want to display the _id of the object which has a structure that looks like this:
by using this line of code:
{backendData && backendData.map((userData) => {
<p key={userData._id}>{userData._id}</p>
})}
I am unsure as to why this line of code doesn't work though because I don't see any output on the next.js page. I am able to receive the backend data as I see the object in my console when I log it but when I try mapping it, it doesn't work. Does anyone know why?

I figured out why, you have to return a value when you map in next.js so the solution would be:
{backendData && backendData.map((userData) => {
return (
<p key={userData._id}>{userData._id}</p>
)
})}

Related

How do I populate a JSON array with the data from my MYSQL database?

So I have a database that I can query using ExpressJS and NodeJS. The Database is a MySQL db. and the data within looks like this:
id: 1
username: 'someUsername'
email: 'randomEmail#email.email'
I want to somehow put the data from within the database into a JSON list and then map over it and show it to the user. Another option to achieve this, I reasoned, would be to populate the state of the app. I've thought of creating some class component, adding a mapStateToProps and assign the data returned from the queries to the state and then use the data from the state in the Reactapp itself. I am not so sure if that would be effective.
This is the minimum code example for a component that fetches data from your backend onLoad, and displaying the data using .map, without using redux (mapstatetoprops)
const DisplayData = () => {
const [ data, setData ] = useState([]);
const fetchData = async () => {
const results = await fetch(url).then(res => res.json());
setData(data)
}
useEffect(() => {
fetchData()
},[])
return ( <div>
{ data.map(item => <p>{item.name}</p> }
<pre>
{ JSON.stringify(null, data, 4) }
</pre>
</div>
}
Well, the return data that you get from the SQL query is itself an array of objects,
Your answer lies in simply iterating over the returned data and assigning it to whatever object you like.
let queryResults = returnedQueryData // data returned from SQL query
let jsonarray = {}
for (row in queryResults) {
jsonarray[row.id] = {
id: row['id'],
username: row['username'],
email: row['email']
}
To access data from the JSON array use
Object.keys(jsonarray).forEach(e => {
// Here e is the object element from the JSON array
}

Getting error when printing json array in EJS variable on console

Guys I am using expressjs, ejs to develop an online shopping website.
Scenario
In order to display products {name, description, imageUrl} I am iterating with the help of ejs control-flow on the webpage.
I am sending an array that contains all the details about each product in JSON format. (from server)
on the client-side when I try to access this array of jsons I get the following error.
(index):266 Uncaught SyntaxError: Invalid or unexpected token
When I opened the sources tab in google chrome it, showed me this
At line number 266. I believe that it is taking this as a string by wrapping the array in double quotes.?
Could anyone tell me what's going wrong with this code?
And by the way, is how I trying to print the array on chrome console
<script>
const data = JSON.parse("<%- products %>");
console.log(data);
</script>
where products are an array of jsons
Backend home route which is sending the JSON array is as follows
router.get("/", async (req, res) => {
let catalogInformation = {};
//getAllProducts returns array of json from the database
const products = await getAllProducts();
catalogInformation.products = products;
userData = {
email: null,
username: null,
};
catalogInformation.userData = userData;
if (req.session.userInformation != null || req.session.userInformation != undefined) {
catalogInformation.userData = req.session.userInformation;
} else {
catalogInformation.userData = {
email: null,
username: null,
};
}
// res.render("catalog", userData);
res.render("catalog", catalogInformation);
return;
});
getAllProducts() method
const getAllProducts = async () => {
const Product = mongoose.model("product", productSchema);
const allProducts = await Product.find();
return allProducts;
};
You don't need to use JSON.parse. Just output the JSON directly:
var data = <%- products %>;
I wouldn't suggest making an AJAX call because you'd be handling 2 requests instead of 1.

React constant with parameters using square brackets

I'm new to React.
I have the code below with a function, but when I run it, it returns an error:
TypeError: renderJson[item.node] is not a function.
How can I fix the renderJson function?
export const readItem = item => {
printlog(item);
return renderJson[item.node](item);
};
const renderJson = {
"heading": item => <h1>{item.map(item => readItem(item))}</h1>
};
If you're trying to create a single React functional component that takes a JSON, and outputs the items in the JSON as a header, it would be more like this:
// If you're getting this JSON from an external source using something like a GET request, put the request inside a "useEffect()" hook
const myJson = {
"heading": ["My First Header", "My Second Header"]
};
export const Header = () => {
console.log(myJson);
return <h1>{myJson.heading.map(header => header}</h1>
};
I apologize if this is a misinterpretation of your question. If it is, any additional details would be helpful.

fetching data with react hook returns undefined on nested obj properties

Im trying to display data that has been fetched. but i cannot seem to display nested objects properties in react. Any ideas? if i log the data i first get a undefined, then the correct data.
my guess is that i need to wait for the data to be loaded then display it. but it does work for the title that is not in a nested obj.
function SingleBeneficiary({ match }) {
const [data, setData] = useState({ data: []});
const id = match.params.id
useEffect(() => {
async function fetchData() {
const response = await fetch(`http://localhost:8081/v1/beneficiary/${id}`);
const jsonData = await response.json()
setData(jsonData)
}
fetchData();
}, [])
return (
{data.title} // works
{data.address.careOf} // dont work
The data
{
"title":"myTitle",
"address":{
"careOf": "my adress"
}
}
Can you try like this?
I set initial data to null, and in return I check if it is not null.
If address can be null, additional null check is required.
function SingleBeneficiary({ match }) {
const [data, setData] = useState(null);
const id = match.params.id
useEffect(() => {
async function fetchData() {
const response = await fetch(`http://localhost:8081/v1/beneficiary/${id}`);
const jsonData = await response.json()
setData(jsonData)
}
fetchData();
}, [])
return (
<div>
{data && (
<div>
<p>data.title</p>
<p>data.address.careOf</p>
</div>
)}
</div>
);
}
You should check if address has careOf property before using it because first time data will be undefined and in second render it will have the data after the api call.
{data.address && data.address.careOf}
For anyone who is having a similar issue(i.e. fetching data via api and only the first time it runs, it will show the data as undefined but after manual refreshing, it works fine), here is a quick and sketchy addition you might consider alongside with 1. "Inline If with Logical && Operator" method and 2. using useState for checking if the api loading is over. With those three, mine worked.
Try fetching the desired data in the previous page of your app; in this case, add the following lines in any page you'll see before "SingleBeneficiary".
const response = await fetch(`http://localhost:8081/v1/beneficiary/${id}`);
const jsonData = await response.json()
Maybe it has to do with npm cache, but not really sure what's going on.
replace
return (
{data.title}
{data.address.careOf}
)
with
return (
{data?.title}
{data?.address?.careOf}
)

Can't handle json files returned by Observable.forkJoin()

I'm working with Angular2 and a nodejs rest api. I have to do one or more http request for a same task so I'm using Observable.forkJoin() to wait for all of them to finish.
I map the result with the json parsing method and then subscribe to this result but I can't get any json properties from the result the way I used to do.
My service method returns the Observable.forkJoin() itself:
public rename(file:MyFile, newName:string){
let requests = new Array();
for(let i=0; i<file.sources.length; i++){
let url:string = this.serverUrl;
if(src.name === "src1"){
url += "rename/src1";
} else if (src.name === "src2" ){
url += "rename/src2";
}
requests[i] = this.http.get(url)
.map((res:Response) => res.json())
.catch(this.handleError);
}
return Observable.forkJoin(requests);
}
Then I subscribe to it in another method elsewhere:
this.api.rename(this.selectedFile, newFileName).subscribe(
rep => {
// The editor tells me "Property 'name' doesn't exist on type '{}'."
console.log(rep[0].name);
},
err => { console.error(err); }
);
The server correctly respond with the data I asked. The rep[0] is correctly set, it looks like this:
Object {name: "res.png", id: "HyrBvB6H-", size: 0, type: "", isShared: falseā€¦}
I suppose it's a typing problem. Usually, with a simple http.get request, it returns an 'any' object. Here it returns an '[]{}' object. res[0] is an '{}' object and I can't get the json properties on it.
Am I using the Observer.forkJoin() correctly? Am I missing something?
Thanks in advance for help :)
If is the editor complaining and it is not an error when the code executes, it likely is a typing problem. You can set the return type of rename() to:
public rename(file:MyFile, newName:string): Observable<any[]> { }
This should allow you access properties of the inner results such as name.
Or you can type the rep array in subscribe() as any[]:
this.api.rename(this.selectedFile, newFileName).subscribe(
(rep: any[]) => {
console.log(rep[0].name);
},
err => { console.error(err); }
);
If all else fails or doesn't work for your solution you can use Type Assertion to treat rep as any[]:
this.api.rename(this.selectedFile, newFileName).subscribe(
rep => {
const responses = rep as any as any[];
console.log(responses[0].name);
},
err => { console.error(err); }
);
If the results structure is consistent across the different endpoints, it would best practice to create an interface/class to replace any[] with.
Hopefully that helps!
http.get is a asynchronous process, so you can't use for loop.
Syntactically you have to nest the gets inside forkJoin, so you have something like this. You can use the for loop to build an array of urls first.:
return Observable.forkJoin([
this.http.get(url[1]).map(res => res.json()),
this.http.get(url[2]).map(res => res.json()),
this.http.get(url[3]).map(res => res.json())
])
.map((data: any[]) => {
this.part1 = data[0];
this.part2 = data[1];
this.part3 = data[2];
});
I wonder if you may be able to do something like this. I'll have a try tomorrow. It's late..
return Observable.forkJoin(let req = [];
for(let i=0; i<file.sources.length; i++){
req[i] = this.http.get(url[i]).map(res => res.json())
}
)