23
loading...
This website collects cookies to deliver better user experience
yarn add vue-query
import { defineComponent } from 'vue';
import { useQueryProvider } from 'vue-query';
export default defineComponent({
name: 'App',
setup() {
useQueryProvider();
},
});
useQueryProvider
provides our app an instance of the QueryClient
class from the react-query/core
package.useQuery
hook allows us to specify our function that fetches data:import { defineComponent } from 'vue'
import { useQuery } from 'vue-query';
...
export default defineComponent({
name: 'Todos',
setup() {
const { data, isLoading, isError } = useQuery(
'todos', // query key
getTodos // fetching function
)
return {
data,
isLoading,
isError
}
}
})
useQuery
the first argument is a simple string. This caches and tracks the result of that query.useQuery
has generic parameters for the type of the data that is being fetched and the error type if a failure occurs:useQuery<Todo[], Error>(
'todos',
getTodos
);
Error
is the standard error object.Todo
type is as follows:type Todo = {
userId: number
id: number
title: string
completed: boolean
}
async function getTodos() {
const response = await fetch('https://jsonplaceholder.typicode.com/');
return response.json();
}
<template>
<div v-if="isLoading">Loading...</div>
<div v-else-if="isError">{{ error!.message }}</div>
<div v-else>{{ JSON.stringify(data) }}</div>
</template>
<script lang="ts">
import { defineComponent } from 'vue'
import { useQuery } from 'vue-query'
type Todo = {
userId: number
id: number
title: string
completed: boolean
}
export default defineComponent({
name: 'Todos',
setup() {
const { data, isLoading, isError, error } = useQuery<Todo[], Error>(
'todos',
getTodos
)
return {
data,
isLoading,
isError,
error
}
}
})
</script>