Technology Stack used: Vue3, REST API and Pinia.
- Define Pinia in
store/pinia.js
and init thedata: {}
object
import { defineStore } from 'pinia'
export const piniaStore = defineStore('counter', {
state: () => ({
data: {}
})
})
- Fetch data from a REST API Endpoint and save it to Pinia store
const fetchData = async () => {
// fetch data from endpoint
const response = await fetch('https://jsonplaceholder.org/posts', {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
}
})
// write in pinia store
store.data = await response.json()
json.value = await store.data
}
- Method
fetchData()
callback after the componentApp.vue
has been mounted
onMounted(() => fetchData())
git clone https://github.com/roma-marshall/vue3-api-pinia
cd vue3-api-pinia
npm run dev
MIT License