DEV Community

Gaurav Srivastava
Gaurav Srivastava

Posted on

Stuck using API's in react

My question is how to fetch and render multiple level API calls.
for example, I called an api using axios, got an array of data. With that array of data got, again called the api's. The same things happens 3-4 times.
The problem is not, how to render this data. But, at the last level, i have to render the data in the form of checkbox and radio. So how to save answers in that case.

You can understand it better with the code...

import {
IonButton,
IonCard,
IonCardContent,
IonCardHeader,
IonContent,
IonHeader,
IonItem,
IonPage,
} from "@ionic/react";
import axios from "axios";
import React, { useEffect, useState } from "react";
import { useParams } from "react-router";
import DisplayQuestion from "../Questions/DisplayQuestion";

const PerformChecklist = () => {
const checkId = useParams();
const [checklist, setChecklist] = useState({
groupIds: [],
id: "",
title: "",
});
const [group, setGroup] = useState([]);
const [question, setQuestion] = useState([]);
const [choice, setChoice] = useState([]);
// fix on which user the checklist is performed, userId
// fix on which vehicle the checklist is performed., vehicleId.

// loading checklist data.
useEffect(async () => {
const response = await axios.get(/checklist/${checkId.id});
const checklistData = response.data.data;
setChecklist({
groupIds: checklistData.groupIds,
id: checklistData._id,
title: checklistData.title,
});
}, []);

// loading category data.
useEffect(() => {
checklist.groupIds.map(async (items) => {
const response = await axios.get(/group/${items});
const groupData = response.data.data[0];
console.log(groupData);
setGroup((group) => [...group, groupData]);
});
}, [checklist]);

// loading question data.
useEffect(() => {
group.map((items) => {
items.questionId.map(async (questionId) => {
const response = await axios.get(/question/${questionId});
const questionData = response.data.data;
setQuestion((question) => [...question, questionData]);
});
});
}, [group]);

useEffect(() => {
question.map((items) => {
items.choices.map(async (choiceId) => {
const response = await axios.get(/choice/${choiceId});
const choiceData = response.data.data;
setChoice((choice) => [...choice, choiceData]);
});
});
}, [question]);

return (


Perform Checklist


size="small"
color="warning"
routerLink="/performactivity"
className="backButton"
>
Back



{checklist.title}





);
};

export default PerformChecklist;

Top comments (0)