marshallswain / feathers-pinia

Connect your Feathers API to the elegant data store for Vue
52 stars 22 forks source link

Auth user state update #149

Open EmileSpecs opened 12 months ago

EmileSpecs commented 12 months ago

Hi

I'm a little confused and unsure if this is supposed to work or not.

I've setup everything as in the basic example setup.

The user is currently logged in, and thus I have a user:

const authStore = useAuthStore()
const user = computed(() => authStore.user)

I then update the user profile using:

const { api } = useFeathers()
const service = api.service('users')

service.patch(user.id, event.data)

As I understand it, the auth service is aware of the user model, and thus updating a user model should also update the user model in the auth service, or am I mistaken?

I've also tried:

service.patch(user.id, event.data)
    .then(() => {
      console.log('User updated')
      auth.reAuthenticate()
    })

The auth.user is still not updated with the changes made.

What am I missing, any help would be appreciated!

EmileSpecs commented 12 months ago

I've managed to get it working using cloning:

const user = computed(() => authStore.user)
const state = user.value.hasClone() || user.value.clone()

function submit (event: FormSubmitEvent<Schema>) {
  busy.value = true

  state.save()
    .then(() => {
      console.log('User updated')
    })
    .catch((error: Error) => {
      console.error(error)
    })
    .finally(() => {
      busy.value = false
    })
}

Interestingly, cloning doesn't seem to work as expected when using SSR (so I've had to disable SSR for this page).

// With SSR enabled
{{ state.__isClone }} // --> true until page load finishes then it become false

// With SSR disabled
{{ state.__isClone }} // --> true

Is this expected behavior? Is there any way to get this to work correctly using SSR?

marshallswain commented 11 months ago

I've not thought of a requirement for using clone during an SSR load. Are you doing full-blown SSR with no client-side JS?

marshallswain commented 11 months ago

If you look here, user is a computed property`: https://github.com/marshallswain/feathers-pinia/blob/main/src/use-auth/use-auth.ts#L50-L55

So the only way that user wouldn't be updating is if something has broken reactivity or created a copy of the data instead of having a reference to the original computed.

marshallswain commented 11 months ago

This should be a guaranteed workaround if you're unable to find what's breaking reactivity:

const { api } = useFeathers()
const auth = useAuthStore() // (or whatever you called the composable, if not useAuthStore)
const user = api.service('users').getFromStore(auth.userId)

user.value should be reactive data from the store.