I followed this tutorial in Vue Apollo for retrieving data with fake api https://www.apollographql.com/blog/frontend/getting-started-with-vue-apollo/.
I however have a code where I use <script setup></script>
instead of the usual setup()
method where everything there is placed.
How should I return data on my elements in this instance?
So this is currently my vue file:
<script setup>
import { storeToRefs } from 'pinia';
import { useAuthStore, useUsersStore } from '@/stores';
import gql from 'graphql-tag'
import { useQuery } from '@vue/apollo-composable'
const authStore = useAuthStore();
const { user: authUser } = storeToRefs(authStore);
const usersStore = useUsersStore();
const { users } = storeToRefs(usersStore);
usersStore.getAll();
apollo: gql`
query Characters {
characters {
results {
id
name
image
}
}
}
`
const { result, loading, error } = useQuery(CHARACTERS_QUERY);
}
</script>
<template>
<div>
<h1>Hi {{authUser?.firstName}}!</h1>
<div v-if="users.loading" class="spinner-border spinner-border-sm"></div>
<div v-if="users.error" class="text-danger">Error loading users: {{users.error}}</div>
<p v-if="error">Something went wrong...</p>
<p v-if="loading">Loading...</p>
<p v-else v-for="character in result.characters.results" :key="character.id">
{{ character.name }}
</p>
<div></div>
</div>
</template>
Then my main.js is:
import { createApp, provide, h } from 'vue';
import { createPinia } from 'pinia';
import App from './App.vue';
import { router } from './helpers';
// setup fake backend
import { fakeBackend } from './helpers';
fakeBackend();
import { ApolloClient, InMemoryCache } from '@apollo/client/core'
import { DefaultApolloClient } from '@vue/apollo-composable'
import { createApolloProvider } from '@vue/apollo-option'
const cache = new InMemoryCache()
const apolloClient = new ApolloClient({
cache,
uri: 'https://rickandmortyapi.com/graphql',
})
const apolloProvider = createApolloProvider({
defaultClient: apolloClient,
})
const app = createApp({
setup () {
provide(DefaultApolloClient, apolloClient)
},
render: () => h(App),
})
app.use(apolloProvider)
app.use(createPinia());
app.use(router);
app.mount('#app');
With the <script setup></script>
it is showing this error?
Seems like you made mistake during copypasting.
Replace this:
apollo: gql`
query Characters {
characters {
results {
id
name
image
}
}
}
`
With this:
const CHARACTERS_QUERY = gql`
query Characters {
characters {
results {
id
name
image
}
}
}
`