#useState question regarding use in <script setup>

3 messages · Page 1 of 1 (latest)

solar rover
#

Setting up a useState
const product = useState('product', () => null);

Watching for the locale to change on the client side:

  if(locale != 'en' || 'en-US') {
    // data is a response from useFetch
    let translatedProduct = data.value.product.locales.find(i => i.locale == newLocale);
    product.value = translatedProduct;
  } else {
    product.value = data.value.product
});```

When accessing the useState in a child component, I can use `{{product.name}}` in the <template> just fine. However if I need to run a find/filter on an array within the product in my `<script /> ` section `console.log(product.links)` returns undefined. 

I also tried `console.log(product.value.links)` what am I missing or not understanding about accessing useState and using it in the script section.

UPDATE: I have added a reproduction link https://stackblitz.com/edit/github-4op7ia?file=components%2Fproduct.vue

I added a timeout to simulate the locale value updating on the client-side. It seems I am not understanding how to properly update useState value

Create a new Nuxt project, module, layer or start from a theme with our collection of starters.

dark sundial
#

Couple of things, firstly product state is null, for obvious reasons your product component cannot access a property of null hence the error. There is no reactivity on the server, so changing your data after the fact shouldn't stop you from validating data in your product component. Check this out as a reference https://stackblitz.com/edit/github-4op7ia-attvir?file=app.vue

Cue

Create a new Nuxt project, module, layer or start from a theme with our collection of starters.

solar rover
#

Thanks for the help @dark sundial , I appreciate your example and have updated my local copy.
Questions I have are:

  1. "There is no reactivity on the server", what do you mean here? I was under the impression that a useState composable was reactive shared state
  2. I still can not understand why I can not access product.value from the <script> section of the <product> component. Reason I want to do this is to run a find function on the links array of the product and set it to a variable so I can use download throughout the component where needed.

const download = product.value.links.find(i => i.title === 'download')

Right now my template looks like
<a :href="product.links.find(i => i.type == 'downloads').url"> {{product.links.find(i => i.type == 'downloads').title }}</a>
and I was trying to clean it up to look like
<a :href="download.url"> {{download.title }}</a>