1

I try to set a value on a property in the "created" lifecycle method - on the server - but the value remains null (its default value).

(I use typescript and class based components)

export default class FunClass extends Vue {
  @Prop() data!: any;
  myProp : any = null;

   created() {
    if (process.server) {
      this.myProp = this.data.interestingData;
    }
  }
}

So there must be some rule that I missed? I tried asyncData but it only works on pages (and I can't access any props from there).

Galivan
  • 4,842
  • 9
  • 44
  • 76
  • 1
    You can either use the `fetch()` hook or `asyncData()` one. Both are a bit different but give you access to quite some things actually. Did you gave a read [to this](https://nuxtjs.org/docs/features/data-fetching#data-fetching)? If you want to access it from anywhere, use the `fetch()` hook. – kissu Apr 27 '22 at 14:54
  • 1
    @kissu Fantastic, that solved the problem. You could add it as an answer if you like. – Galivan Apr 27 '22 at 15:33

1 Answers1

1

If you want to handle your data on any place (page, component, layout etc...), you can use the fetch() hook, it's quite handy thanks to it's helpers like $fetchState.pending and it's not blocking, hence you could display some nice skeletons while the data is loading, like Instagram/Facebook.

For more info, you can check this documentation regarding data fetching in Nuxt.

If you want to have more differences regarding fetch() vs asyncData, here is a handy question wit plenty of various great answers.

kissu
  • 40,416
  • 14
  • 65
  • 133