Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Question]: When is the session server side available? Initial authorized api request possible? #88

Closed
silvio-e opened this issue May 16, 2024 · 4 comments
Labels
question Further information is requested

Comments

@silvio-e
Copy link
Contributor

silvio-e commented May 16, 2024

I call my endpoint /api/countries which is doing a request to an external API which needs info from the session. That works fine.

But when I call my api route on the initial loading of the app, for example in app.js in a callOnce, it seems that the session is not available yet.

// This seems not to work

await callOnce(async () => {
  const result = await $fetch('/api/countries')
})

Am I doing something wrong or is this correct behavior?

The idea was to fetch data and filling the store on app load. How can this be achieved with using a token from the authentication?

@amandesai01
Copy link

amandesai01 commented May 22, 2024

what is app.js? you mean app.vue?

But yeah, ideally it should work, since this module injects a plugin in nuxt app which initilaises session before any of the UI code gets executed.

It would be great if you can provide a minimal reproduction.

Copy link
Owner

Atinux commented May 22, 2024

@silvio-e you need to use useRequestFetch(), see nuxt/nuxt#24813

@Atinux Atinux added the question Further information is requested label May 22, 2024 — with Volta.net
@silvio-e
Copy link
Contributor Author

@Atinux Awesome, thank you! I saw it being mentioned but didn't find it in the docs, so I didn't even try. But now it works for me in this scenario:

// useCountriesStore.ts

export const useCountries = defineStore('countries', () => {
  const countries = ref()

  const fetch = async () => {
    try {
      countries.value = (await useRequestFetch()<ApiResponse<Country>>('/api/countries')).results
    }
    catch (error) {
      console.log(error)
    }
  }
  return { countries, fetch }
})
// app.vue

const countries = useCountries()

await callOnce('countries', async () => {
  await countries.fetch()
})

Is that usage correct?

@silvio-e
Copy link
Contributor Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Further information is requested
Projects
None yet
Development

No branches or pull requests

3 participants