Search code examples
javascriptreactjsjsontypescriptfetch

How to fetch data from a specific JSON file?


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>
  );
}


Solution

  • 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>
      );
    }

    Screenshot