0

I am Fetching data from an API in my Native App and displaying it as a List.

Below is my code:

async componentWillMount() {
    if (Platform.OS === 'android') {
        BackHandler.addEventListener('hardwareBackPress', this.backPressed);
    }
    this.fetchNotifications();
}
}

async fetchNotifications() {
    this.setState({refreshing: true});

    const config = getAppConfig();
    const cognitoToken = await this.getCognitoToken(config);
    if (cognitoToken !== null) {
        let headers = await this.getRequestHeaders(cognitoToken);
        let body = this.getRequestBody(config);
        let notificationUrl = config["notification-retrieve-api"];

        return fetch(notificationUrl,
            {
                method: 'POST',
                headers: headers,
                body: body
            }).then((response) => {
            if (response.ok) {
                return response.json();
            } else {
                throw new Error('Something went wrong');
            }
        })
        .then((notifications) => {
            console.log(JSON.stringify(notifications));
            this.setState({
                notifications,
                error: null,
                refreshing: false
            });
        }).catch((error) => {
            this.setState({
                notifications: [],
                error,
                refreshing: false
            });
        });
    }
}

This works fine. I can retrieve the data from the API.

Now I want to separate the API code from my screen component. I will be calling "fetchNotifications" as a function in my screen component. I am trying to do so but it's not working at all.

This is what I'm doing:

async componentWillMount() {
    if (Platform.OS === 'android') {
        BackHandler.addEventListener('hardwareBackPress', this.backPressed);
    }
    let response = fetchNotifications();

    this.setState({
        notifications: response,
        error: null,
        refreshing: false
    })
}
}

async function fetchNotifications() { //now this function is in another component
.
.
.
.

    if(cognitoToken !== null) {
        let headers = await this.getRequestHeaders(cognitoToken);
        let body = this.getRequestBody(config);
        let notificationUrl = config["notification-retrieve-api"];

        return fetch(notificationUrl,
            {
                method: 'POST',
                headers: headers,
                body: body
            }).then((response) => {
            if (response.ok) {
                response.json();
            } else {
                throw new Error('Something went wrong');
            }
        })
        .then((response) => {
            return response;
        }).catch((error) => {
            this.setState({
                notifications: [],
                error,
                refreshing: false
            });
        });
    }
}

export default fetchNotifications;

Is this way correct? Anyone with a better solution?

1 Answer 1

1

My two cents, I always put async task in Promise, including API requests.

// API helper file
export const fetchNotifications = (params) => {
return new Promise(async (resolve, reject)=>{
    try{
       const headers = getHeaders(params)
       const body = getBody(params)
       const response = await fetch(notificationUrl,
        {
          method: 'POST',
          headers: headers,
          body: body
        })
          if (response.ok) {
            const responseObj = await response.json();
            resolve(responseObj)
          } else {
            throw new Error('Something went wrong');
          }
    } catch (e) {
        // something went wrong
        generalHandler(e) // logging etc. 
        reject(e) // for ui handling
    }
}
}

then we can use it everywhere

import { fetchNotifications } from '.../APIHelper'

In your ui file :

componentWillMount() {
   fetchNotifications(params)
       .then((notifications) => {
          console.log(JSON.stringify(notifications));
          this.setState({
            notifications,
            error: null,
            refreshing: false
          });
        }).catch((error) => {
          this.setState({
            notifications: [],
            error,
            refreshing: false
          });
        });
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.