Home > other >  ReactJS print nested JSON inside a function using map((item, index))
ReactJS print nested JSON inside a function using map((item, index))

Time:11-12

I am deveoping a Kanban Board. I use ReactJS to call the backend for stages and tasks that are open in each stage. It is a very simple JSON that I get from the backend.

JSON

[
  {
    "open_tasks": [
      {
        "task_id": 37,
        "task_title": "Develop frontend"
      },
      {
        "task_id": 38,
        "task_title": "Create app"
      }
    ],
    "stage_id": 6,
    "stage_title": "Tasks"
  },
  {
    "open_tasks": [],
    "stage_id": 15,
    "stage_title": "Blocked"
  },
  {
    "open_tasks": [],
    "stage_id": 18,
    "stage_title": "Finished"
  }
]

Now I want to use ReactJS to print the nested JSON, however I cannot use map inside a map.

import { useEffect, useState } from "react";

export function IndexKanbanBoard() {
  const [stagesWithOpenTasks, setStagesWithOpenTasks] = useState(() => []);

  // Load stages
  const loadStagesWithOpenTasksForBoard = async (e) => {
    let result = await fetch("https://localhost:5002/api/kanban_boards/get_stages_with_open_tasks_for_board", {
      method: "GET",
      headers: {
        'Authorization': 'Bearer '   'bla bla'
      }
    });
    let resultJson = await result.json();
    if (result.status === 200) {
      setStagesWithOpenTasks(resultJson.map(fetch_object => {
        return fetch_object
      }))
    }
  };

  // On load
  useEffect(() => {
    loadStagesWithOpenTasksForBoard()
  }, []);

  return (
    <div>
      {stagesWithOpenTasks.map((item, index) => (
        <div key={index}>
          <h2>{item.stage_title}</h2>

          <p>I WANT TO SHOW open_tasks HERE</p>
        </div>
      ))}
    </div>
    );
}
  
export default IndexKanbanBoard;

How can i loop trough nested JSON in ReactJS?

CodePudding user response:

Assigning the next array items to a variable will help please have a look

  return (
    <div>
      {data.map((item, index) => {
        const openTasks = item["open_tasks"];
        return (
          <div key={index}>
            <h2>{item.stage_title}</h2>
            {openTasks.map((item) => (
              <p>{item.task_title}</p>
            ))}
            <p></p>
          </div>
        );
      })}
    </div>
  );
  • Related