Shuffle Vue arrays twice: once in server-side rendering and once in the browser

Is there a way to shuffle an array and then pass it to a component? It seems to work when accessing the page directly with nuxt-link.

<template>
  <div>
  
    <CardsMetalCard :myCategory="myCategory" :catMetal="catMetal" />
  </div>
</template>
computed: {
...mapGetters("design", {
  designCategory: ["category"],
}),

myCategory() {
  var result = this.designCategory.find((i) => i.url === this.category);
  this.catMetal = result.metal;
  var newRelatedArray = this.designCategory.filter(
    (i) =>
      i.metal === result.metal 
  );
  // The shuffle method is used to sort the array before returning
  return this.shuffle(newRelatedArray);
},

},

Everything seems to be functioning correctly with nuxt-link. However, upon refreshing the page, the array gets shuffled twice - once during SSR and then again in the browser. As a result, my component loads data from the server-side rendered shuffle and then renders again with the browser-generated shuffle. This leads to a discrepancy in the final component value due to mismatched objects.

Answer №1

Strange behavior when dealing with variable data

After finding a solution in response to the aforementioned question, I attempted to retrieve data using an async Fetch() method that would function correctly in both server-side rendering and on the browser.

async fetch() {
    var designCategory = await this.$store.getters["design/category"];
    var result = designCategory.find((i) => i.url === this.category);
    this.catMetal = result.metal;
    var newRelatedArray = designCategory.filter(
      (i) => i.metal === result.metal 
    );

    this.myCategory = this.shuffle(newRelatedArray);
  },

Fortunately, this approach proved successful.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What could be causing the Logical Or to fail in my function?

How can I adjust the following sample code to check for not only empty keys but also null and undefined? I attempted: (obj[key] !== '' || obj[key] !== null || (obj[key] !== undefined) However, that approach caused issues and did not function c ...

"Utilize the UpdateOne function in MongoDB to add a value from a different field

Attempting to add an existing field of my document to an array. Here is the schema: const mySchema = new Schema({ level: { type: Number, default: 1 }, mHierarchy: [ { userId: { type: mongoose. ...

How can a bootstrap gallery maintain a consistent size despite variations in picture dimensions?

I am currently working on creating an image gallery for our website using the latest version of Bootstrap. However, we are facing an issue with the varying sizes of our images. Each time the gallery switches to a new image, it disrupts the overall size and ...

Determine the object ID of an element in the array at index x if you are already aware of the array[x]->ID

Suppose we have the following array from a previous question... How do I locate the [X]=> stdClass Object where the [id] of this object is [id] => 9??? Array ( [0] => stdClass Object ( [id] => 8 [book_catego ...

Generate a shared key using two distinct values, regardless of their initial order

Let's consider this scenario: I have two keys, key1 = "abc" and key2="xyz". I am looking to create a function that can output the same result regardless of the order in which the parameters are input. For instance, calling foo(key1, key2) or foo(key ...

vb.net form with client-side validation using jquery

I am facing an issue with a VB.NET form button that needs to go through jQuery validation before executing a function in the code behind. The problem is, regardless of whether the validation is true or false, the function stops and never calls the VB.NET f ...

Can we determine if a user has accessed a link by opening it in a new tab?

Is there a way to distinguish if a user on your website opens another link (also to your website) in a new tab from them just clicking on the link normally? Whether it's through javascript, server-side processing, or any other method. I assume that d ...

Having trouble populating the box with CSS through JavaScript

https://i.sstatic.net/HH00Z.png Currently working on a quiz website using JavaScript, and trying to dynamically fill the color in the box as the quiz progresses with the help of CSS. However, facing some challenges with the code implementation. Any sugges ...

Displaying AJAX data in Django using an HTML table

My Django template currently has the following AJAX script running: function create_table() { $.ajax({ method: "GET", url: "/api/data/", success: function(data){ console.log('button clicked') ...

Incorporate HTML dynamic table data into a consolidated INSERT query

On my Main Page, dynamic rows are being added inside a table using jQuery. I have a varying number of rows to add and need to perform SQL insert statements for all of them, each containing 4 different textfields. In simpler terms, I have elements (1,2,3,x ...

"Encountering a duplicate key error when reordering columns in PrimeVue's DataTable component

I have encountered an unusual issue with a datatable: <DataTable :scrollable="true" :value="shipments" :totalRecords="shipments.length" :reorderableColumns="true" :alwaysShowPaginator="fal ...

Trigger a Vue.js action once an element is generated using v-if

One of the challenges I am facing is loading an element based on a condition (v-if). <div id="food-content" v-if="activeFood" v-cloak> To load it, I use this line of code: app7.activeFood = food; After the element is instantiated, I aim to apply ...

What is the best way to locate the desired number from a group of three numbers in JavaScript?

Is there a way to determine if "x" is equal to any of the numbers 15, 30, 70, or 140? const x =....; if(x===?){....}else{....} ...

What is the best way to extract data from a proxy in VUE3?

Currently, I am utilizing the ref() function to store data retrieved from Firebase. However, when attempting to filter and retrieve a single record, the outcome is not as expected. Instead of returning a single object, something different is being displaye ...

The variable was not defined immediately after being assigned a value

Having some trouble with iterating through an array that is assigned to a variable in my code editor. Despite using console.log(variable_name.length) and successfully getting the array length, I keep getting an error saying the variable is undefined when t ...

The useEffect function is triggered repeatedly in React when not using Strict mode

I am encountering an issue where the connect function is being called multiple times instead of just once, resulting in a WebSocket connection failure message in the browser: VM1867 bundle.js:41684 WebSocket connection to 'ws://localhost:3000/chat/2 ...

Utilizing vue-router-next without a bundler: A step-by-step guide

Previously, the vue-router plugin would automatically mount to the global application instance like this: if (inBrowser && window.Vue) { window.Vue.use(VueRouter); } In Vue 3, this functionality has been restricted. So, how can I access VueRoute ...

Error message "Uncaught in promise" is being triggered by the calendar function within the Ionic

Can someone assist me in creating a calendar feature for my app? My concept involves a button with text that, when clicked by the user, opens a calendar. However, I am encountering an error message: ERROR Error: Uncaught (in promise): TypeError: Cannot set ...

Refresh HTML with JSON/AJAX

Ever since I discovered JSON for handling AJAX functionality in my rails applications, I've been hooked. Using RJS to render HTML just didn't sit right with me as it felt like it was violating the MVC pattern. My first project that heavily utiliz ...

Should the updater method be placed in the state or passed directly to the context?

Is it better to have this context setup like so: <MatchContext.Provider value={this.state.match}> Or should I structure it as follows in my state? match: { match: null, updateMatch: this.updateMatch }, Which approach is more eff ...