Reputation:
I have one issue with fetching data from a json file.
The json file has some sub arrays and I want to map it. I created a codesandbox page and need help for mapping the related data: https://codesandbox.io/s/json-data-fetch-c00rf
When you open the link you will see that I have used React fetching with useEffect but it is not restricted with that, that means you can use another thing.
The json data coming from here: https://web-coding-challenge.vercel.joyn.de/api/blocks
Here is the code as well:
import "./styles.css";
import React, { useState, useEffect } from "react";
export default function App() {
const [todos, setTodos] = React.useState<any[]>([]);
React.useEffect(() => {
fetch(`https://web-coding-challenge.vercel.joyn.de/api/blocks`)
.then((results) => results.json())
.then((data) => {
setTodos(data);
});
}, []);
return (
<div className="App">
{todos.map((post: any) => (
<div>
<h1>{post.id}</h1>
<h2>{post.assets.primaryImage.url}</h2>
</div>
))}
</div>
);
}
Upvotes: 0
Views: 1256
Reputation: 50346
The response constains assets as an nested array. So you can use reduce and get all the elements in one array and then iterate it to create list
import "./styles.css";
import React, { useState, useEffect } from "react";
export default function App() {
const [todos, setTodos] = React.useState<any[]>([]);
React.useEffect(() => {
fetch(`https://web-coding-challenge.vercel.joyn.de/api/blocks`)
.then((results) => results.json())
.then((data) => {
const responseData = data.reduce((acc:any,curr:any)=>{
const assets = curr.assets;
acc.push(...assets)
return acc ;
},[])
setTodos(responseData);
});
}, []);
return (
<div className="App">
{todos.map((post: any) => (
<div>
<h1>{post.id}</h1>
<h2>{post.primaryImage.url}</h2>
</div>
))}
</div>
);
}
Upvotes: 0
Reputation: 10297
You can map through the post.assets
and return your required jsx
For an example here I'm listing all the urls in a list
return (
<div className="App">
{todos.length && todos.map((post: any) => (
<div>
<h2>{post.id}</h2>
<ul>
{post.assets.map((asset: any, index: number)=>{
return (
<li key={index}>{asset.primaryImage.url}</li>
)
})}
</ul>
</div>
))}
</div>
);
Upvotes: 0