0

So I have been working on a react native application just like the meetups app. It has its own node.js backend which can be viewed here https://github.com/rahullakhaney/meetup/tree/master/meetup-backend While in my application, I am trying to populate the groups from my database, I get this error "Possible unhandled promise rejection (id:0) null is not an object"

Here is my api.js file

import axios from 'axios';

axios.defaults.baseURL = 'http://localhost:3000/api';

const fakeGroupId = '58d64e3a122149dd3cdba5d8';

class MeetupApi {
  constructor() {
    this.groupId = fakeGroupId;
    this.path = `/groups/${this.groupId}/meetups`;
  }

  async fetchGroupMeetups() {
    const { data } = await axios.get(this.path);

    return data.meetups;
  }

}

export {
  MeetupApi
};

You can also view the complete code at https://github.com/rahullakhaney/meetup/tree/master/meetup-mobile

Can anyone please explain why am I getting this error, sorry but I am new to react native.

Rahul Lakhaney
  • 109
  • 1
  • 7

1 Answers1

0

Every function or method declared with the async keyword returns a promise. That promise is resolved when you return something from that function and it is rejected when you throw an exception in that function.

When you write this:

const { data } = await axios.get(this.path);

then what really happens is that you add a resolve callback to the promise returned by axios.get() but every rejection of that promise returned by axios.get() is raised as an exception inside of the fetchGroupMeetups() method. You don't use try/catch so that exception propagates and is in turn converted into a rejection of the promise that is returned by fetchGroupMeetups() - which you probably don't handle.

To handle that rejection you either need to use it as something like:

x.fetchGroupMeetups(...).catch(err => console.log('Error:', err));

or, inside of other async function:

try {
  x.fetchGroupMeetups(...);
} catch (err) {
  console.log('Error:', err);
}

but of course doing something more than just printing the error.

To know more details on what are those unhandled rejections and why you should always handle them, see this answer:

TL;DR: The unhandled rejections used to be warnings but will now crash your app. Here is why.

rsp
  • 107,747
  • 29
  • 201
  • 177