0

So I am kinda stuck on something and I wanted to see if I can get some clarify on how to set the API response to some local variables and extract the data.

So here are the function where I am getting the API response:

function make_request(url) {
    return fetch(url, {
        method: 'GET',
        headers: new Headers({
            'Authorization': 'Basic ' + btoa(USERNAME + ':' + PASSWORD),
        }),
    }).then(response => response.json());
}

function get_offices() {
    let offices = make_request('https://sample-api.com');
    offices.then(function(response) {
        console.log(response);
        return response;
    });
}

This is the response:

enter image description here

Now outside the function, I want to set a local variable as this:

let table_data = get_offices.data.offices - This is not working and coming back as undefined.

I would like the table_data to look like this:

let table_data = [
    {
        'id': 'ID',
        'state': 'State'
    },
    {
        'id': 'ID',
        'state': 'State'
    }
];

I would also like set another variable and define the pagination inside like this:

let settings = {
    'page': get_offices.pagination.current_page,
}

This is also coming back as undefined, all help would be appreciated!

  • get_offices is a function so you need to call it. Where are you setting these variables, can you share more of the component or function where you want to call get_offices? – Scott Gnile May 11 '21 at 12:39
  • how can you call, `offices.then`? `offices` is not a promise I guess. – Hari Kishore May 11 '21 at 12:41
  • 1
    @kishore — `offices` is the return value of `make_request` which clearly is a promise. It is `get_offices.pagination` which is undefined. – Quentin May 11 '21 at 12:42

1 Answers1

-1

Mane the function asyn cand use await

async function get_offices() { let offices = await make_request('https://sample-api.com'); return offices }

Habeeb Rahman
  • 320
  • 1
  • 3
  • 15