Sergey
Sergey

Reputation: 81

nuxt js acces to component data from server side

Is there any way to access from serverside to component data or props ?

I have test app with test component with template

<template>
<div>
  <h1>TEST PAGE</h1>
  <p>counter : {{counter}}</p>
</div>
</template>

In asyncData() I start a timer

asyncData(context)
{
  console.log('in server process')
    console.log(context)
    let timerId = setInterval(() => {

     ..... some logic
    }, 4000);
    return {counter : 15};
  },
}

SO question, how posible change the counter value dynamicaly in template? I need do it on server side for some reason Thanks!

Upvotes: 1

Views: 1574

Answers (2)

zernonia
zernonia

Reputation: 188

I think you should make an API call to your backend during AsyncData lifecycle. You can refer to this Nuxt example here .

Returning a Promise

export default {
  asyncData( context ) {
    return axios.get(`https://my-api/counter`).then(res => {
      return { counter: res.data.counter}
    })
  }
}

Upvotes: 1

knkbga
knkbga

Reputation: 141

asyncData method runs way earlier and only once before loading of the page. It is performed before initialization of the component.

reference: Nuxt Lifecycle, asyncData

Solution:

You can watch the property and send an async request (using libraries like axios / fetch) to let the server know and handle it on the server.

Upvotes: 2

Related Questions