I am currently working on a Project management app, and I would like to dynamically display data from GET request, however I have no idea how to do it and thats why I could use some help, insight from more experienced folks. I would like to figure out how to store and then access data from the GET response.
My script:
export default {
setup() {
type Project = {
title: string;
author: string;
description: string;
};
type GetProjectResponse = {
data: Project[];
};
async function getProject() {
try {
const response = await fetch(
'https://sill-api-app.herokuapp.com/api/project/622b1a17a900330b46af2203',
{
method: 'GET',
headers: {
Accept: 'application/json',
},
}
);
if (!response.ok) {
throw new Error(`Error! status: ${response.status}`);
}
const result = (await response.json()) as GetProjectResponse;
console.log(JSON.stringify(result, null, 4));
return result;
} catch (error) {
if (error instanceof Error) {
console.log('error message: ', error.message);
return error.message;
} else {
console.log('unexpected error: ', error);
return 'An unexpected error occurred';
}
}
}
void getProject();
console.log();
return {
getProject,
};
},
name: 'singleProject',
};
The project is done in Quasar(VueJS) and I am using typescript. This code snippet is the script part of my View.
You need a wrap of fetch function like this:
function api<T>(url: string): Promise<T> {
return fetch(url).then(response => {
if (!response.ok) {
throw new Error(response.statusText)
}
return response.json<T>()
})
}
api<Project >('v1/posts/1').then((projectData:Project) => {
console.log(title, message)
}).catch(error => {
/* show error message */
})