Implement ES6 classes for managing state in the vuex store within a Nuxt application

After setting an ES6 class to the state in my vuex store in nuxt, I encountered the following warning:

 WARN  Cannot stringify arbitrary non-POJOs EndPoint

However, when I use an object as the state, it works without any warnings.

So the question arises, how can I effectively utilize ES6 classes in my state?

Below is my model:

export default class EndPoint {
    constructor(newEndPoints) {
        this.login = newEndPoints.login;
        this.status = newEndPoints.status;
    }
}

and this is how I mutate the state:

commit(CoreMutations.SET_ENDPOINTS, new EndPoint(response.data));

When using an object:

const EndPoint = {
    endPoints(newEndPoints) {
        return {
            login: newEndPoints.login,
            status: newEndPoints.status
        };
    }
};

and mutating as follows:

commit(CoreMutations.SET_ENDPOINTS, EndPoint.endPoints(response.data));

Answer №1

After a thorough discussion in the comments, it was determined that adding a toJSON method to the class would resolve the issue when setting the state on the client side. However, it was noted that setting the state on the server side would result in the states becoming undefined. To address this, the following code was suggested:

    toJSON() {
        return Object.getOwnPropertyNames(this).reduce((a, b) => {
            a[b] = this[b];
            return a;
        }, {});
    }

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

How can I retrieve the SID received in a different tab using MSAL.js?

I have successfully integrated MSAL into a client-side library, and things are going smoothly so far. My next goal is to enable Single Sign-On (SSO) by following the instructions provided in the documentation at https://learn.microsoft.com/en-us/azure/act ...

Struggling to pass data changes between child components in Vuejs2?

Encountering a challenge with my current project. I have implemented a vuejs2 parent-child structure as outlined below Parent app child product-list product product-image colour-select In the product template, I initialize the sibling components ...

Issues with AngularJS compatibility on Internet Explorer 8

Recently, I've been developing a new Angular app and I'm trying to ensure that it's compatible with IE8. It seems like the app is loading in the routing information and the template partially, but I keep encountering an error in the console ...

Preventing direct URL access with Angular redirects after refreshing the page

My website allows users to manage a list of users, with editing capabilities that redirect them to the /edit-user page where form information is preloaded. However, when users refresh the page with F5, the form reloads without the preloaded information. I ...

Why does the Node promise chain execute .then despite encountering an error?

When a promise chain encounters an error, why does it not execute .then unless the .then references an external method with a parameter? In this particular example, I intentionally throw an error in the promise chain. The first three .then methods do not ...

The count of bits is not producing the anticipated result

Attempting to tackle the challenge of Counting Bits using JavaScript, which involves determining the number of set bits for all numbers from 0 to N, storing them in an array, and returning the result Let me provide an explanation Input: n = 5 ...

Looking for a solution to the problem: Module 'import-local' not found

internal/modules/cjs/loader.js:596 throw err; ^ Error: Cannot find module 'import-local' at Function.Module._resolveFilename (internal/modules/cjs/loader.js:594:15) at Function.Module._load (internal/modules/cjs/loader.js:520:25) Encoun ...

Exploring the art of reading and writing to a file with JavaScript and NodeJS

I am currently working on creating a function that will scan a file and remove all content below a specific line before adding new lines to the file. So far, I have successfully read the file and identified the target line: function analyze() { lineRe ...

Difficulty occurred when trying to import Polymer components

Currently, I am in the process of learning how to utilize Polymer. I meticulously followed the instructions provided exactly as specified here. However, upon reaching step 3 and adding the import for paper-checkbox, an error presented itself: Error: A c ...

Introducing Vuetify 3's v-file-input with interactive clickable chips!

I noticed an unexpected issue with the v-file-input component in Vuetify3. In Vuetify 2, it was possible to use the selection slot to customize the display of selected files. This functionality still works in both versions, as mentioned in the documentatio ...

The array's value fluctuates into a negative without any direct manipulation from my end

In order to work with the $scope.option value, I stored it in a temporary variable and then applied operations on the temporary variable after changing all the values of $scope.option to negative numbers. var app = angular.module('myApp', []); ...

Adding images to your SVG using Bobril is a simple process that can add visual

I have been attempting to insert an image into an SVG using Bobril, but the following code is not functioning as expected: { tag: 'svg', children: { tag: 'image', attrs: { 'xlink:href': &ap ...

Issue found in factory and service dependencies

To retrieve user information, the factory sends a request to the API using ApiRequest.sendRequest: (function() { angular.module('isApp.user', []) .factory('UserProfileFactory', function( $log, ApiRequest, dataUrls ) { // User pr ...

What is the best way to retrieve the output of MongoDB's collection.aggregate() within a NodeJS callback function?

In my database, I have a users collection with the following data: { "_id" : ObjectId("5b29ba37cd0b1726068731c3"), "name" : "Gym Dog", "profilePicUrl" : "https://i.imgur.com/mPStaKV.png", "totalProgress" : { "goal" : 300, "progress ...

Fulfill the promise within the $stateProvider and proceed with utilizing the outcomes

I am facing an issue where I need to resolve a promise in a state provider so that I can use the results of the promise in another promise. I am a bit unsure about how to go about this. I tried the following approach: app .config(['$stateProvid ...

Is there a comparable solution like Fabric in Javascript or Node.js?

One thing that I really appreciate about Fabric is how it simplifies the deployment process to multiple servers, especially with its strong support for SSH. But since our project is based on node.js, it would be ideal if we could achieve a similar function ...

Is it possible to refresh AdSense banner when the router changes?

Is there a way to reload the AdSense banner ads when the router changes? I've been encountering issues trying to re-add the script and HTML properly. Any guidance on how this should be done would be greatly appreciated... This is just a test for one ...

What is the best way to generate all possible combinations between two arrays of objects?

I am faced with the challenge of combining two arrays of objects, named origin and destination, to generate a final array that contains all possible combinations from the two arrays. For instance: origin = [ { id: 1, regionName: "Africa North&q ...

What is the best way to replicate a synchronous ajax call? (mimicking synchronous behavior with asynchronous methods)

Given that a "native" synchronous ajax call can block the user interface of the browser, it may not be suitable for many real-world scenarios (including mine). I am curious to know if there is a way to mimic a synchronous (blocking) ajax call using an asy ...

What is the best way to transmit a Blob object to the server without it arriving empty?

I'm currently facing an issue where I am attempting to send a Blob object containing video data to my server for upload to my S3 storage. However, the Blob is arriving as an empty object on the server side. const blob = new Blob(videoChunks, { t ...