draw134
draw134

Reputation: 1187

ReactJS using Ionic Uncaught TypeError: Cannot read property 'map' of undefined from axios request

I got a schedules.ts file and I got a function getSchedules()

import axios from 'axios'

export default function getSchedules(){
    const config = {
        headers: { Authorization: 'Bearer ' + localStorage.getItem('bearer_token') ,
        Accept: 'application/json',
        'Content-Type': 'application/json',
        }
    };
     return axios.get('http://127.0.0.1:8000/api/auth/getSchedules',config).
      then((res)=>{
       return res.data
      }).catch((err)=>{
        console.log(err)
      })
}

In my Tab1 component, I want to get the data from my axios request and display by using array.map

import getSchedules from '../methods/schedules'

const Tab1: React.FC = () => {

  const [schedules, setSchedules] = React.useState([]);

  React.useEffect(() => {
    getSchedules().then(data => setSchedules(data.schedules));
  }, []);


  return (
    <IonPage>
      <IonHeader>
        <IonToolbar>
          <IonTitle>Appointments</IonTitle>
        </IonToolbar>
      </IonHeader>
      <IonContent className="ion-padding">
    <IonList>

      {schedules.map(elem => {
        return(
          <IonItem key={elem['id']}>
          <IonLabel>
            <h2>{elem['schedule_type']}</h2>
            <h3>{elem['type']}</h3>
            <h3>{elem['start_date']}</h3>
          </IonLabel>
        </IonItem> 
        )
      })}

    </IonList>
  </IonContent>
    </IonPage>
  );
};
export default Tab1;

But when I go to the component I got

Tab1.tsx:38 Uncaught TypeError: Cannot read property 'map' of undefined

I am new to react and this typescript thing. I wish i can use v-for like in vue.js. Can someone tell me what is the problem of this and how can I solve? Thanks..

Upvotes: 0

Views: 121

Answers (1)

Robin Zigmond
Robin Zigmond

Reputation: 18249

The problem turned out to be that the data coming back from the API had no schedules property, so setSchedules(data.schedules) is making schedules undefined. The data as a whole is already the desired array, so what is needed is to call setSchedules with data as the argument.

That is, the body of useEffect should be

getSchedules().then(data => setSchedules(data));

which can, if you prefer, be simplified as

getSchedules().then(setSchedules);

Upvotes: 1

Related Questions