1

I have routes set up for a local api. So I am trying to retrieve the api data console log just the data. But whenever I run my code it console logs the entire promise. Any ideas on how to help?

This is my code:

const onPageLoad = async () => {
    const response = await fetch(`/api/project/projects`, {
        method: 'GET',
        headers: { 'Content-Type': 'application/json' },
    })
    
    if (response.ok) {
        console.log(response.json())

    } else {
        console.error(err)
    }
}

onPageLoad();

This is what shows in the console log:

screenshot of console log

Mike 'Pomax' Kamermans
  • 49,297
  • 16
  • 112
  • 153
optionalfigure
  • 269
  • 1
  • 2
  • 9

1 Answers1

1

You can await the promise from response.json() to get its value:

const onPageLoad = async () => {
    const response = await fetch(`/api/project/projects`, {
        method: 'GET',
        headers: { 'Content-Type': 'application/json' },
    })
    
    if (response.ok) {
        let value = await response.json();
        console.log(value);
        // potentially do something else with value
        return value;
    } else {
        console.log('fetch() promise succeeded, but not with response.ok', response.status);
        throw new Error(`Got status ${response.status}`);
    }
}

onPageLoad().then(() => {
    console.log('all done');
}).catch(err => {
    console.log(err);
});
jfriend00
  • 683,504
  • 96
  • 985
  • 979