0
votes

Im writing code in Vue 3 using composition API. I use Vuex store. I got Dashboard component which is used by route '/' and by ':userId'.

setup() {
    const store = useStore()
    const route = useRoute()
    const router = useRouter()
    const userProfile = computed(() => store.state.userProfile)
    const users = computed(() => store.state.users)
    const userId = computed(() => route.params.userId).value
    let user
    if (userId) {
      user = computed(() => users.value.filter((user) => user.id === userId)[0])
      console.log('user', user) // returns undefined!
    } else {
      user = computed(
        () => users.value.filter((user) => user.id === userProfile.value.id)[0]
      )
      console.log('user', user) // works well! Returns current user
    }

    return {
      user
   }
}

Why is that the first console.log is not working after refreshing page on ":userId" path. And the second one for "/" path works well?

Thank you for help

1
Is user.id string? From router parameters you always get string, so if it is number you should use user.id === Number(userId) or user.id === parseInt(userId) - Leszek Mazur
Thats correct! Thank you, dziękuję :) - Damian Wójcik

1 Answers

0
votes

Do parse it before doing the comparison using === because it does type comparison as well.

user = computed(() => users.value.filter((user) => user.id === parseInt(userId, 10)[0])