Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unhandled Runtime Error TypeError: events.map is not a function

I’m fetching data using graphQL but wen I render in the page
it says Unhandled Runtime Error TypeError: events.map is not a function

useState don’t know if this correct?

const [events, setEvents] = useState < any > ([]);

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const fetchEvents = async () => {
    const requestBody = {
      query: `
      query{
        events{
          _id
          title
          date
          price
          description
          creator {
            _id
            email
          }
        }
      }
      `
    };

    setLoading(true);
    await fetch(`http://localhost:8888/graphql`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(requestBody)
    }).then(res => {
      if (res.status !== 200 && res.status !== 201) {
        throw new Error('Failed!');
      }
      return res.json();
    }).then(resData => {
      //console.log(resData);
      const events = resData.data.events;
      setEvents({ events: events })
    }).catch(err => {
      console.log(err);
    })
  }
  {
   loading ? events.map((data: any, index: any) =>
    <p key={index}>{data.title}</p>
    )
    :
    <p>Loading</p>
   }

my console.log
enter image description here

>Solution :

You are getting "TypeError: events.map is not a function" error because events is an object, not an array. You are using setEvents({ events: events }) instead of setEvents(events) to set the state.

Changing setEvents({ events: events }) to setEvents(events) should fix it.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading