I want to get all users on store initialization and store fetched users in users
state, I think this is better for performance, when the component where i need to display users is rendered, the component will not need to fetch users and wait for users to be fetched, instead it will just grab users from the store, but this will not work as getAll
is not defined so it will give error Cannot read properties of undefined (reading 'getAll')
, instead i should fetch users in getAll
function and them set the users state, How can i call getAll
function on store initialization ?
import { defineStore } from 'pinia';
import axios from 'axios'
const baseUrl = 'http://localhost:80';
useUsersStore.getAll()
export const useUsersStore = defineStore({
id: 'users',
state: () => ({
users: this.getAll(), // where getAll() returns users directly instead of setting the users state.
}),
actions: {
getCookie(name) {
const value = document.cookie
const parts = value.split(name)
if (parts.length === 2) {
return parts.pop().split(';').shift()
}
},
async getAll() {
try{
const csrfToken = this.getCookie('XSRF-TOKEN')
this.users = axios.get(`${baseUrl}/api/users`, {
headers: {
'X-XSRF-TOKEN': decodeURIComponent(csrfToken)
},
withCredentials: true
}).then(response=> this.users = response.data.users)
}catch(error){
console.log(error);
}
},
}
});
You can call the getAll
function at the point where you initialize your store.
You can modify your code like this:
import { defineStore } from 'pinia';
import axios from 'axios';
const baseUrl = 'http://localhost:80';
export const useUsersStore = defineStore({
id: 'users',
state: () => ({
users: [],
}),
actions: {
async getAll() {
try {
const csrfToken = this.getCookie('XSRF-TOKEN');
const response = await axios.get(`${baseUrl}/api/users`, {
headers: {
'X-XSRF-TOKEN': decodeURIComponent(csrfToken)
},
withCredentials: true
});
this.users = response.data.users;
} catch (error) {
console.log(error);
}
},
getCookie(name) {
const value = document.cookie;
const parts = value.split(name);
if (parts.length === 2) {
return parts.pop().split(';').shift();
}
},
},
});
// Call getAll at the point of store initialization
const usersStore = useUsersStore();
usersStore.getAll();
Now, when the store is initialized, getAll
will be called automatically, fetching users from the API and setting them in the store's state.