MuhtasimMusfiqZarab
9/5/2019 - 3:01 AM

asyncData()

This is the way to use asyncData inside of vue (paged) component.

////////////----------------------------------------------------------------------

// special property on the pages components (only) that nuxt will execute on the server
  // server waits for it to finish and then return it to the client (hence we will get a pre-rendered complete page back to the client)
  // this also replaces the data() as well as created() in the client side (this executes on the server)
  // we cant use normal data then which will override the asyncData & can get unwanted effect
  // inside of async ==> we get this.$route.params(params object holds all route parameters) by using context.params (or context.route.params)
  // we also know that this keyword can't be used here
  // for individual data we still always perform async because it might need some extra data
  // we can only use asyncData() inside of a paged component
  //async data will be executed on the server wehn we load it the first time or on client on subsiquent navigation & action
  // this is powerfull for page specific data

  //---------fetch vs asyncData
  //* async merge the data in data property, fetch stores the data on the store (using commit inside it)
  // better option than fetch is to use nuxtServerInit()
  asyncData(context) { //callback arg is not used, so nuxt does not wait that to be called
    // this keyword does not work as expected in async data coz async data runs before this component is created
    // we need to give asyncData the idea about when we are done (otherwise imediately returns the finished page
    // one solution is to return a promise ( thus it waits for the promise to be resolved and gives the result)
    // the syntax is return new Promise() which is to wrap the whole setTimeout
    // other one is to use callback (in aync data we get two arguments (context, callback)), execute callback when we are done
    // execution of callback method tells the async method that we are done
    // we use callback instead of return
    return new Promise(resolve => {
      setTimeout(() => {
        //if first arg is not null then it returns error autometically
        resolve({
          loadedPosts: [
            {
              id: "1",
              title: " First Post",
              previewText: "This is the first post",
              thumbnail:
                "https://images.pexels.com/photos/1509428/pexels-photo-1509428.jpeg?auto=compress&cs=tinysrgb&dpr=3&h=750&w=1260"
            },
            {
              id: "2",
              title: " Second Post",
              previewText: "This is the second post",
              thumbnail:
                "https://images.pexels.com/photos/1509428/pexels-photo-1509428.jpeg?auto=compress&cs=tinysrgb&dpr=3&h=750&w=1260"
            },
            {
              id: "3",
              title: " Third Post",
              previewText: "This is the third post",
              thumbnail:
                "https://images.pexels.com/photos/1509428/pexels-photo-1509428.jpeg?auto=compress&cs=tinysrgb&dpr=3&h=750&w=1260"
            }
          ]
        });
      }, 1500);
      //once resolved then marge data with other component data (inside then)==>(map the data as needed using new obj or return the object as a whole)
      // catching errors inside of promise
      // then handles resolve , catch handles reject
    })
      .then(data => {
        console.log(data);
        return data;
      })
      .catch(e => console.log(new Error()));
  }
  
  
  
  //-------------CALLBACK PATTERN------------------------------
  
  //--------------Later version----------------------
  asyncData(context, callback) {
    //data must wait till it finish loading on the server before it is send to client (thus must use callback or promise)
    setTimeout(() => {
      callback(null, {
        loadedPost: {
          id: "1",
          title: " First Post (id " + context.params.id + ")",
          previewText: "This is the first post",
          author: "Muhtasim Musfiq",
          updatedDate: new Date(),
          content: "Dummy text, not the preview text",
          thumbnail:
            "https://images.pexels.com/photos/1509428/pexels-photo-1509428.jpeg?auto=compress&cs=tinysrgb&dpr=3&h=750&w=1260"
        }
      });
    }, 1000);
  }
  
  
  
  //---------------------------async data using backend----------------
  asyncData(context) {
    //callback is not needed as we are using promise
    return axios
      .get(
        "https://nuxt-blog-e3c31.firebaseio.com/post/" +
          context.params.id +
          ".json"
      )
      .then(res => {
        //merging with component data (loadedData)
        return {
          loadedPost: res.data
        };
      })
      .catch(e => context.error(e));
    //id is fetched from route params (context.params.id === route.params.id)