I have this function in my Pinia store:
async function getCurrentUser(){
let user: User | undefined = undefined;
if (auth.currentUser?.uid) {
user = await getUserById(auth.currentUser.uid)
state.value.currentUser = user;
}
}
So, inside a component I just need to call:
userStore.getCurrentUser();
And I will get access to the current user from the state:
userStore.state.currentUser
But this approach confuses me, because we are mutating the state inside the get function.
Therefore, I think it would be better to do this (inside a component):
userStore.state.currentUser = await getUserById(auth.currentUser.uid)
userStore.state.currentUser //Do whatever you want
Which option is better? I can't make up my mind.
This question is more about the approach rather than the specific implementation (in the form of the getCurrentUser function)
I think it would be more appropriate to rename the function to setCurrentUser()
rather than getCurrentUser()
to make its purpose clearer and avoid confusion. By using the naming convention of set followed by the name of the state property, it indicates that the function is responsible for updating the currentUser
state in the Pinia store.
In Pinia, it is common to provide separate functions for reading and updating the state. The store exposes the state object for components to read, allowing them to access the current user using userStore.state.currentUser
. To update the state, components can call the setCurrentUser()
function in the store