rodro1

async data nuxt call axios serversite and clientside

May 10th, 2021 (edited)
27
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.52 KB | None | 0 0
  1. The simplest answer is data() is processed on the client side, however asyncData() section is processed on the server side on the call for Nuxt() once and on the client side once more.
  2.  
  3. The biggest advantage of nuxt is it's ability to render content on the server side. If you load your content using promise on the client side, say for example in the mounted section as:
  4.  
  5. data() {
  6. return {
  7. products: []
  8. }
  9. },
  10.  
  11. mounted() {
  12. axios.get('/api/v1/products').then(response => {
  13. this.products = response.data
  14. })
  15. }
  16. the javascript code is sent to the client as it is and the browser is responsible to run the promise to fetch the data from the api. However if you put the promise inside asyncData:
  17.  
  18. asyncData() {
  19. return axios.get('/api/v1/products').then(response => {
  20. // Note that you can't access the `this` instance inside asyncData
  21. // this.products = response.data
  22. let products = response.data
  23. return { products } // equivalent to { products: products }
  24. })
  25. }
  26. The data fetching is done on the server side and the result is pre-rendered and an html with the data (rendered into it) is sent to the client. So in this case the client won't be receiving the javascript code to process the api call by itself, but instead it receives something like this:
  27.  
  28. <ul>
  29. <li>
  30. <a href="#">Product 1</a>
  31. </li>
  32. <li>
  33. <a href="#">Product 2</a>
  34. </li>
  35. <li>
  36. <a href="#">Product 3</a>
  37. </li>
  38. </ul>
  39. The result we return from asyncData is merged with what is in data. It's not replaced but merged.
Add Comment
Please, Sign In to add comment