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:

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);
});