0

I want to send data from Data function to asyncData in Nuxt.

I have tried this

  data () {
    return {
      prevpage: null,
      nextpage: null,
      currentPage: 2,
      pageNumbers: [],
      pageNumberCount: 0
    }
  },
  asyncData ({ $axios, error, data }) {
    return $axios
      .get('https://api.themoviedb.org/3/movie/popular?api_key=' + process.env.API_SECRET + '&page=' + this.currentPage)
      .then((response) => {
        return {
          popularmovies: response.data.results
        }
      })
      .catch((e) => {
        error({
          statusCode: 503,
          message: 'Unable to fetch event'
        })
      })

I also tried this

  .get('https://api.themoviedb.org/3/movie/popular?api_key=' + process.env.API_SECRET, {
    params: {
      page: this.currentPage
    }

I also tried to use ES6

  .get(`https://api.themoviedb.org/3/movie/popular?api_key=${process.env.API_SECRET}&page=${this.currentPage}`)

But it always returned error

Cannot read property 'currentPage' of undefined

1
  • The asyncData hook is executed before the data option is available Commented Sep 26, 2020 at 19:39

2 Answers 2

2

You can use the VueX store

asyncData ({ $axios, error, data , store}) {
   // access to data

   console.log(store.state.myData)

 }) 

in your mounted set data to the store

mounted(){

this.$store.setData(this.pageNumberCount)


}
Sign up to request clarification or add additional context in comments.

Comments

0

It would be better to add a URL parameter for the page, instead of having it inside the local state. Then you can use it with the params property of the context object passed to asyncData.

For example, you can use something like /page/_currentPage.vue inside your pages directory, then you can rewrite your asyncData declaration to be something like asyncData ({ $axios, error, data, params}) and use params.currentPage to access the page received as a parameter. You should also check if it exists, and if it doesn't you can just set the page to 1

2 Comments

I don't understand, can you please elaborate. Thanks
I've added an example. Feel free to ask again if it doesn't help

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.