I have a simple hello world app where I am trying to parse a typescript object. Before I had done with Vue 2 class components, and I am sure the issue is the Transition to vue is just unfamiliar.
The issue with the below method is here
if (response != null) {
state.name = JSON.parse(response.getName())
state.age = parseInt(JSON.parse(response.getAge()))
}
error in console
Error while getting the response: TypeError: response.getName is not a function
Home class
<script lang="ts">
import {api} from "@/lib/api";
import {reactive} from "vue";
export default {
name: "Home",
setup() {
const state = reactive({
name: '',
age: '',
mode: process.env.NODE_ENV,
myName: process.env.VUE_APP_TITLE
})
const submit = async () => {
try {
const response = await api.getTest()
if (response != null) {
state.name = JSON.parse(response.getName())
state.age = parseInt(JSON.parse(response.getAge()))
}
} catch (error) {
console.log('Error while getting the response:', error)
}
}
return {
...state,
submit
}
},
}
</script>
api.ts
export const api = {
async getTest() {
try{
return await grpcClient.get<TestResponse>("/v1/test")
.then(res => {
return res.data <-- json but would be nice if it was a TS object
})
}catch (err) {
console.log("error" + err);
}
},
}
error in console:
Error while getting the response: TypeError: response.getName is not a function
at eval (Home.vue?4912:19:1)
but even is I used
state.name = JSON.parse(response).name
I get issues with accessing the object
My assumption was that Vue 3 had better Typescript support which is why Class components were deprecated.
How can I get my gRPC typescripts objects intergraded with my vue components?
The solution is I had to create a new TypeScript interface. I am not able to use the generated gRPC ones.
interface Test {
name: string;
age: string
}
Axios request:
async getTest() {
try{
return await grpcClient.get<Test>("/v1/test")
.then(res => {
return res.data
})
}
catch (err) {
console.log("error" + err);
}
},
Then to use it this:
setup() {
const state = reactive({
username: '',
age: '',
})
const submit = async () => {
try {
const response = await api.getTest()
if (response != null) {
state.username = response.name
state.age = response.age
console.log("I am the state " + state.username)
}
} catch (error) {
console.log('Error while getting the response:', error)
}
}
return {
...state,
submit
}
}