Search code examples
javascriptreactjsaxios

React Unable To Get Response from API to populate in JSX


I've confirmed that an API call I'm making does return the results I want, but for some reason those results are not showing up in the UI. I'm stuck at this point, any pointers would be appreciated.

import React, { useState } from "react";
import axios from 'axios';
import Button from '@mui/material/Button';
import moment from 'moment';

export default function Appointments({ teacher_id, date }) {
    const [appointments, setAppointments] = useState([]);

    function updateAppointments(data) {
        setAppointments(data);
    }

    function getAppointmentsForTeacherForDate(teacher_id, date) {
        axios.get(`http://localhost:3000/api/v1/teachers/${teacher}/appointmentsForDate/`,
          { params: { teacher_id: teacher_id, date: date }},
          {withCredentials: true}
        ).then(response => {
          if (response.data.appointments) {
            updateAppointments(response.data.appointments);
          } else {
            console.log("Failed to get appointments for teacher");
          }
        })
    }
    
    return (
        <>
            <div>
                {
                    appointments?.map(appt => {
                        <div key={appt.id}>
                            <h2>{appt.start_datetime}</h2><br></br>
                            <h2>{appt.teacher.first_name}</h2><br></br>
                            <h2>{appt.status}</h2>
                        </div>
                    })
                }
            </div>
        </>
    );

}

Currently, this is returning nothing at all, even though the API response shows an array of appointments when I log to console.


Solution

  • In your rendering logic, you're utilizing the Array.map function incorrectly. When curly braces {} are used in a map function without a return statement, nothing is shown because the JSX elements are not returned.

    The solution to this problem is to return the JSX elements from the map method using parentheses ().

    when i array length > 0 then listing the data otherwise NO DATA FOUND!

     return (
            <>
                <div>
                    {appointments.length > 0 ? (
                        appointments.map(appt => (
                            <div key={appt.id}>
                                <h2>{appt.start_datetime}</h2>
                                <h2>{appt.teacher.first_name}</h2>
                                <h2>{appt.status}</h2>
                            </div>
                        ))
                    ) : (
                        <div>No appointments found</div>
                    )}
                </div>
            </>
        );