I’m trying to get data from local data with pinia and nuxt, and it can’t seam to get the end point, what’s wrong with my code?
I’m new to Vue, Nuxt and Pinia, I have been following some tutorial, but I can’t get to get data from the end point, here is my code.
#stores/blogStore.js
import { defineStore } from 'pinia';
export const usePostStore = defineStore('post', {
state: () => ({
posts: [],
loading: false,
error: null
}),
getters: {
postCount: (state) => state.posts.length,
draftPosts: (state) => state.posts.filter((post) => post.status === 'draft'),
publishedPosts: (state) => state.posts.filter((post) => post.status === 'published'),
isDraft: (state, id) => state.posts.find((post) => post.id === id)?.status === 'draft',
truncatedPosts: (state) => state.posts.map((post) => post.content.substring(0, 20) + '...'),
},
actions: {
async getPosts() {
this.loading = true
console.log(this.loading)
const api = "http://localhost:3000/posts"
const res = await fetch(api)
console.log
if (!res.ok) {
this.error = res.statusText
return;
}
const data = await res.json();
this.posts = data;
this.loading = false;
},
},
});
#app.vue
<template>
<div v-if="store.loading">
Loading ...
</div>
<div>
<div> You have {{ store.postCount }} Blogs </div>
<div v-for="post in store.posts" :key="post.id">
<div>{{ post.title }}</div>
<div>Views: {{ post.view_count }}</div>
<br />
</div>
</div>
</template>
<script setup>
import { usePostStore } from './stores/blogStore'
const store = usePostStore()
</script>
I have tried several back end like local json-server and django rest framework with no results but when I add the data inside the posts:[] it’s correctly displaying the data in the html.
How can I successfully fetch data from an endpoint?
2
Answers
Adding
store.getPosts()
on the scripts setup loaded the data likethis did the magic.
The main problem is with the fake endpoint you’re trying to interact with.
Try this endpoint
https://my-json-server.typicode.com/typicode/demo/posts
which is suited for testing purposes!Or maybe this endpoint
https://dummyjson.com/posts
with many information to interact with!