I am trying to map a Json response to a Typescript model. I tried to generate the typescript models, and although they did generate, they're sadly not working correctly. Therefore, I am exploring creating my own models in hopes to find out my the generated gRPC Typescript models did not work.
I will note using the axios response works fine. Example
})}`).then(res => {
return res.data
})
then in the calling component
const posts = async () => {
try {
const response = await api.getAllTodos()
if (response != null) {
todoArr.value = response.todo
}
return response
} catch (error) {
console.log('Error while getting the response in home posts:', error)
}
}
However, I want to return a Typescript object because the above posts
method causes linting issues. I would prefer to access them directly with getter and setters.
Full example of axios call:
const grpcClient: AxiosInstance = axios.create({
baseURL: url.baseUrl,
headers: {
'content-type': 'application/json',
},
});
async getAllTodos() {
try {
return await grpcClient.get<ITodoAllResponse>(`/v1/getAll?${qs.stringify({
})}`).then(res => {
const { data } = res
console.log("res in getAll", data)
return data
})
} catch (err) {
console.log("error" err);
}
},
export interface ITodoAllResponse {
todos: Array<Todo>;
}
How can I map my axios response to a Typescript model?
---- update 1 ----
I updated my models
export interface ITodo {
id: string;
title: string;
}
import { ITodo } from "./Todo";
export interface ITodoAllResponse {
todos: ITodo[];
}
error in console
Error while getting the response in home posts: TypeError: Cannot read properties of undefined (reading 'title')
however data.todo.title
does exist.
res in getAll {todo: Array(5)} todo: Array(5)
CodePudding user response:
Seems like in your response data image it's todo: Todo[]
and you have todos: Todo[]
in your interface