In my vue.js application, I'm trying to display text using TypeScript. Here is an example of the JSON response:
{
"data": [
{
"firstName": "Foo",
"lastName": "Smith"
},
{
"firstName": "Mike",
"lastName": "vue"
},
{
"firstName": "go",
"lastName": "lang"
}
],
"metadata": "none"
}
Using TypeScript:
export interface TestResponse {
firstName:string;
lastName:string;
}
Axios call:
const request: AxiosInstance = axios.create({
baseURL: url.baseUrl,
headers: {
'content-type': 'application/json',
},
//params: {base64_encoded: 'true', fields: 'stdout'},
});
export const api = {
async getTest() {
try{
return await request.get<TestResponse>("/v1/test")
.then(res => {
console.log("lastname " + res.data.lastName);
return res.data
})
}catch (err) {
console.log("error" + err);
}
},
}
However, it always shows undefined. I have tried using TestResponse[]
and Array<TestResponse>
without success.
Instead of getting an array as expected, I receive the error message:
Cannot read properties of undefined (reading 'data')
export default {
name: "Test",
setup() {
const firstName = ref('');
const lastName = ref('');
const submit = async () => {
try {
const response = await api.getTest()
if (response != null) {
firstName.value = response[0].data.firstName
lastName.value = response[0].data.lastName
console.log("I am a name " + response.lastName)
}
} catch (error) {
console.log('Error while getting the response:', error)
}
}
return {
firstName,
lastName,
submit
}
},
};