Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react-native fetch async/await response filtering

I have response from my server like buildings : [record1, record2, ...] and I want to get only the array from that response. How can I get just the array from the Promise? I have tried some async/await things but I didn't understand how to use it in this code:

setupImpagination() {
    ....
    fetch(pageOffset, pageSize, stats) {
        return fetch(`http://localhost:3000/api/building/all?skip=${pageOffset}&limit=${pageSize}`)
            .then(response => {
            console.log('response.json() => ',response.json());
            response.json()
            })
            .catch((error) => {
            console.error(error);
            });

    }
    });
}
like image 579
imalik8088 Avatar asked Dec 04 '22 21:12

imalik8088


1 Answers

.then way

 fetch(pageOffset, pageSize, stats) {
        return fetch(`http://localhost:3000/api/building/all?skip=${pageOffset}&limit=${pageSize}`)
            .then(response => {
               console.log('response.json() => ',response.json());
               response.json()
            }).then(responseJson => {
               return responseJson.buildings
            }).catch((error) => {
               console.error(error);
            });

        }
    });

async/await way:

 async fetch(pageOffset, pageSize, stats) {
       try {
           const response = await fetch(`http://localhost:3000/api/building/all?skip=${pageOffset}&limit=${pageSize}`);
           const responseJson = await response.json();
           return responseJson.buildings;
       } catch(error){
            console.error(error);
       }
like image 132
Alexander Vitanov Avatar answered Dec 06 '22 09:12

Alexander Vitanov