skip to Main Content

I am trying to map loop in React. Below is the json but it’s showing map is not a function. How can I get data from api through map function like below the json?

{
  "message": "Successfully loaded data.",
  "courseData": [
    {
      "id": 3,
      "user_id": "1",
      "trainer_id": "2",
      "course_name": "Admin Full Support",
      "regular_price": "12000",
      "discount_price": "8000",
      "trainer": null,
      "photo": "https://itder.com/storage/uploads/course/8655491729531301.png",
      "status": "1",
      "created_at": "21-10-2024 17:21:41",
      "updated_at": "21-10-2024 17:21:41",
      "trainer_data": {
        "id": 2,
        "user_id": "1",
        "name": "Bashir Ahmed",
        "phone": "01947225599",
        "details": "Hi",
        "photo": "https://itder.com/storage/uploads/trainer/6951221729531073.png",
        "status": "1",
        "created_at": "21-10-2024 17:17:53",
        "updated_at": "21-10-2024 17:17:53"
      }
    },
    {
      "id": 1,
      "user_id": "1",
      "trainer_id": "1",
      "course_name": "English",
      "regular_price": "200",
      "discount_price": "100",
      "trainer": null,
      "photo": "https://itder.com/storage/uploads/course/4624191729512058.png",
      "status": "1",
      "created_at": "21-10-2024 12:00:58",
      "updated_at": "21-10-2024 12:00:58",
      "trainer_data": {
        "id": 1,
        "user_id": "1",
        "name": "Masud Akbar",
        "phone": "01897865456",
        "details": "hi",
        "photo": "https://itder.com/storage/uploads/trainer/5702571729512011.png",
        "status": "1",
        "created_at": "21-10-2024 12:00:11",
        "updated_at": "21-10-2024 12:00:11"
      }
    },
    {
      "id": 7,
      "user_id": "1",
      "trainer_id": "3",
      "course_name": "Facebook Ad Campaign",
      "regular_price": "500",
      "discount_price": "100",
      "trainer": null,
      "photo": "https://itder.com/storage/uploads/course/7190441729599935.jpeg",
      "status": "1",
      "created_at": "22-10-2024 12:25:35",
      "updated_at": "22-10-2024 12:25:35",
      "trainer_data": {
        "id": 3,
        "user_id": "1",
        "name": "Dhrubo Jyoti Das",
        "phone": "01774444000",
        "details": "hi",
        "photo": "https://itder.com/storage/uploads/trainer/4606921729531092.png",
        "status": "1",
        "created_at": "21-10-2024 17:18:12",
        "updated_at": "21-10-2024 17:18:12"
      }
    },
    {
      "id": 6,
      "user_id": "1",
      "trainer_id": "3",
      "course_name": "Graphics  Full Support",
      "regular_price": "12500",
      "discount_price": "12000",
      "trainer": null,
      "photo": "https://itder.com/storage/uploads/course/5304721729531416.png",
      "status": "1",
      "created_at": "21-10-2024 17:23:36",
      "updated_at": "21-10-2024 17:23:36",
      "trainer_data": {
        "id": 3,
        "user_id": "1",
        "name": "Dhrubo Jyoti Das",
        "phone": "01774444000",
        "details": "hi",
        "photo": "https://itder.com/storage/uploads/trainer/4606921729531092.png",
        "status": "1",
        "created_at": "21-10-2024 17:18:12",
        "updated_at": "21-10-2024 17:18:12"
      }
    },
    {
      "id": 5,
      "user_id": "1",
      "trainer_id": "3",
      "course_name": "Medical Admission",
      "regular_price": "25000",
      "discount_price": "22000",
      "trainer": null,
      "photo": "https://itder.com/storage/uploads/course/1433531729531385.png",
      "status": "1",
      "created_at": "21-10-2024 17:23:05",
      "updated_at": "21-10-2024 17:23:05",
      "trainer_data": {
        "id": 3,
        "user_id": "1",
        "name": "Dhrubo Jyoti Das",
        "phone": "01774444000",
        "details": "hi",
        "photo": "https://itder.com/storage/uploads/trainer/4606921729531092.png",
        "status": "1",
        "created_at": "21-10-2024 17:18:12",
        "updated_at": "21-10-2024 17:18:12"
      }
    },
    {
      "id": 4,
      "user_id": "1",
      "trainer_id": "4",
      "course_name": "Python Engineering",
      "regular_price": "25000",
      "discount_price": "22000",
      "trainer": null,
      "photo": "https://itder.com/storage/uploads/course/2878081729531330.png",
      "status": "1",
      "created_at": "21-10-2024 17:22:10",
      "updated_at": "21-10-2024 17:22:10",
      "trainer_data": {
        "id": 4,
        "user_id": "1",
        "name": "Mojaddid-E-Alfe Sany",
        "phone": "01733165886",
        "details": "hi",
        "photo": "https://itder.com/storage/uploads/trainer/7753901729531123.png",
        "status": "1",
        "created_at": "21-10-2024 17:18:44",
        "updated_at": "21-10-2024 17:18:44"
      }
    },
    {
      "id": 2,
      "user_id": "1",
      "trainer_id": "1",
      "course_name": "The Complete WordPress Website Course",
      "regular_price": "18000",
      "discount_price": "15000",
      "trainer": null,
      "photo": "https://itder.com/storage/uploads/course/9298281729531272.png",
      "status": "1",
      "created_at": "21-10-2024 17:21:12",
      "updated_at": "21-10-2024 17:21:12",
      "trainer_data": {
        "id": 1,
        "user_id": "1",
        "name": "Masud Akbar",
        "phone": "01897865456",
        "details": "hi",
        "photo": "https://itder.com/storage/uploads/trainer/5702571729512011.png",
        "status": "1",
        "created_at": "21-10-2024 12:00:11",
        "updated_at": "21-10-2024 12:00:11"
      }
    }
  ],
  "status_code": 201
}

Here is what I have tried. This data coming from Postman.

const [course, setCourse] = useState([]);

useEffect(() => {
  fetch('https:examplewebsite///')
  .then(res => res.json())
  .then(data => setCourse(data))
  .catch(error => console.log(error))
}, [])

console.log(course);
{
  course.map((crs, index) => {
    <div key={index}>
      <h1>{crs.message}</h1>
      {courseData.map((crsdt) => {
        <div>
          <h1>{crsdt.id}</h1>
        </div>;
      })}
    </div>;
  });
}

2

Answers


  1. You initialize course as an array:

    const [course, setCourse] = useState([]);
    

    And expect it to be an array:

    course.map((crs, index) => {
    

    However, you update it to the JSON response in its entirety:

    .then(data => setCourse(data))
    

    That JSON response is not an array. It’s an object. If the goal is to set state to the courseData property on that object, set it to the property value:

    .then(data => setCourse(data.courseData))
    

    Alternatively, you can make your state an object from the start:

    const [course, setCourse] = useState({courseData:[]});
    

    And continue to update it to the whole JSON response:

    .then(data => setCourse(data))
    

    And in the markup you’d loop over the array:

    course.courseData.map((crs, index) => {
    

    Overall you also seem to be very confused about the structure of your data, the names of your variables, etc. For example, here you try to access a message property:

    <h1>{crs.message}</h1>
    

    But the objects in the array over which you’re iterating have no such property. The parent object from the overall JSON does, though.

    You’re also referencing a variable that you never declare:

    courseData.map(crsdt => {
    

    So it’s not really clear what you’re trying to loop over or accomplish here.

    If the goal is to show the top-level "message" and then loop over the courseData property then that might look like this:

    <div>
      <h1>{course.message}</h1>
      {
        course.courseData.map(crsdt => {
          <div>
            <h1>{crsdt.id}</h1>
          </div>
        })
      }
    </div>
    
    Login or Signup to reply.
  2. The issue is, map is a method in array objects, and the object in the code is not an array.

    You may still get your desired output subject to some adjustments in the code. Please see below the output got here by applying the adjustments. If the output looks what is expected, then you may kindly go through the following sections. This post has been made in such a way that your own code will be followed. As you know, there are other possibilities as well.

    Test run – output

    Browser display on load of the app

    Browser display on load of the app

    The details of adjustments

    a. The object retrieved to be enclosed in an array as below.

    The original statement

     .then((data) => setCourse(data))
    

    The adjusted code

     .then((data) => setCourse([data]))
    

    b. return statement is to be provided in three places

    Original code

    {
      course.map((crs, index) => {
        <div key={index}>
          <h1>{crs.message}</h1>
          {courseData.map((crsdt) => {
            <div>
              <h1>{crsdt.id}</h1>
            </div>;
          })}
        </div>;
      });
    }
    

    Adjusted code

      return course.map((crs, index) => {
        return (
          <div key={index}>
            <h1>{crs.message}</h1>
            {crs.courseData.map((crsdt) => {
              return (
                <div>
                  <h1>{crsdt.id}</h1>
                </div>
              );
            })}
          </div>
        );
      });
    

    Full listing of the code adjusted

    Note : Instead of fetch, an equivalent async code has been applied.

    App.js

    import { useState, useEffect } from 'react';
    
    export default function App() {
      const [course, setCourse] = useState([]);
    
      useEffect(() => {
        new Promise((resolve) => {
          setTimeout(() => {
            resolve(data);
          }, 1000);
        })
          .then((data) => setCourse([data]))
          .catch((error) => console.log(error));
      }, []);
    
      console.log(course);
      return course.map((crs, index) => {
        return (
          <div key={index}>
            <h1>{crs.message}</h1>
            {crs.courseData.map((crsdt) => {
              return (
                <div>
                  <h1>{crsdt.id}</h1>
                </div>
              );
            })}
          </div>
        );
      });
    }
    
    const data = {
      message: 'Successfully loaded data.',
      courseData: [
        {
          id: 3,
          user_id: '1',
          trainer_id: '2',
          course_name: 'Admin Full Support',
          regular_price: '12000',
          discount_price: '8000',
          trainer: null,
          photo: 'https://itder.com/storage/uploads/course/8655491729531301.png',
          status: '1',
          created_at: '21-10-2024 17:21:41',
          updated_at: '21-10-2024 17:21:41',
          trainer_data: {
            id: 2,
            user_id: '1',
            name: 'Bashir Ahmed',
            phone: '01947225599',
            details: 'Hi',
            photo: 'https://itder.com/storage/uploads/trainer/6951221729531073.png',
            status: '1',
            created_at: '21-10-2024 17:17:53',
            updated_at: '21-10-2024 17:17:53',
          },
        },
        {
          id: 1,
          user_id: '1',
          trainer_id: '1',
          course_name: 'English',
          regular_price: '200',
          discount_price: '100',
          trainer: null,
          photo: 'https://itder.com/storage/uploads/course/4624191729512058.png',
          status: '1',
          created_at: '21-10-2024 12:00:58',
          updated_at: '21-10-2024 12:00:58',
          trainer_data: {
            id: 1,
            user_id: '1',
            name: 'Masud Akbar',
            phone: '01897865456',
            details: 'hi',
            photo: 'https://itder.com/storage/uploads/trainer/5702571729512011.png',
            status: '1',
            created_at: '21-10-2024 12:00:11',
            updated_at: '21-10-2024 12:00:11',
          },
        },
        {
          id: 7,
          user_id: '1',
          trainer_id: '3',
          course_name: 'Facebook Ad Campaign',
          regular_price: '500',
          discount_price: '100',
          trainer: null,
          photo: 'https://itder.com/storage/uploads/course/7190441729599935.jpeg',
          status: '1',
          created_at: '22-10-2024 12:25:35',
          updated_at: '22-10-2024 12:25:35',
          trainer_data: {
            id: 3,
            user_id: '1',
            name: 'Dhrubo Jyoti Das',
            phone: '01774444000',
            details: 'hi',
            photo: 'https://itder.com/storage/uploads/trainer/4606921729531092.png',
            status: '1',
            created_at: '21-10-2024 17:18:12',
            updated_at: '21-10-2024 17:18:12',
          },
        },
        {
          id: 6,
          user_id: '1',
          trainer_id: '3',
          course_name: 'Graphics  Full Support',
          regular_price: '12500',
          discount_price: '12000',
          trainer: null,
          photo: 'https://itder.com/storage/uploads/course/5304721729531416.png',
          status: '1',
          created_at: '21-10-2024 17:23:36',
          updated_at: '21-10-2024 17:23:36',
          trainer_data: {
            id: 3,
            user_id: '1',
            name: 'Dhrubo Jyoti Das',
            phone: '01774444000',
            details: 'hi',
            photo: 'https://itder.com/storage/uploads/trainer/4606921729531092.png',
            status: '1',
            created_at: '21-10-2024 17:18:12',
            updated_at: '21-10-2024 17:18:12',
          },
        },
        {
          id: 5,
          user_id: '1',
          trainer_id: '3',
          course_name: 'Medical Admission',
          regular_price: '25000',
          discount_price: '22000',
          trainer: null,
          photo: 'https://itder.com/storage/uploads/course/1433531729531385.png',
          status: '1',
          created_at: '21-10-2024 17:23:05',
          updated_at: '21-10-2024 17:23:05',
          trainer_data: {
            id: 3,
            user_id: '1',
            name: 'Dhrubo Jyoti Das',
            phone: '01774444000',
            details: 'hi',
            photo: 'https://itder.com/storage/uploads/trainer/4606921729531092.png',
            status: '1',
            created_at: '21-10-2024 17:18:12',
            updated_at: '21-10-2024 17:18:12',
          },
        },
        {
          id: 4,
          user_id: '1',
          trainer_id: '4',
          course_name: 'Python Engineering',
          regular_price: '25000',
          discount_price: '22000',
          trainer: null,
          photo: 'https://itder.com/storage/uploads/course/2878081729531330.png',
          status: '1',
          created_at: '21-10-2024 17:22:10',
          updated_at: '21-10-2024 17:22:10',
          trainer_data: {
            id: 4,
            user_id: '1',
            name: 'Mojaddid-E-Alfe Sany',
            phone: '01733165886',
            details: 'hi',
            photo: 'https://itder.com/storage/uploads/trainer/7753901729531123.png',
            status: '1',
            created_at: '21-10-2024 17:18:44',
            updated_at: '21-10-2024 17:18:44',
          },
        },
        {
          id: 2,
          user_id: '1',
          trainer_id: '1',
          course_name: 'The Complete WordPress Website Course',
          regular_price: '18000',
          discount_price: '15000',
          trainer: null,
          photo: 'https://itder.com/storage/uploads/course/9298281729531272.png',
          status: '1',
          created_at: '21-10-2024 17:21:12',
          updated_at: '21-10-2024 17:21:12',
          trainer_data: {
            id: 1,
            user_id: '1',
            name: 'Masud Akbar',
            phone: '01897865456',
            details: 'hi',
            photo: 'https://itder.com/storage/uploads/trainer/5702571729512011.png',
            status: '1',
            created_at: '21-10-2024 12:00:11',
            updated_at: '21-10-2024 12:00:11',
          },
        },
      ],
      status_code: 201,
    };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search