Error: Vuex commit fails due to JSON circular structure issue

Using Vue.js along with the vuex store, I make an API call to validate an item, which returns arrays of errors and warnings.

Below is my vuex action :

export function validateitemReview ({ commit, dispatch, state }, { reviewId, type, itemreviewData }) {
  console.log('*** validateItemReview() called')
  return api.post(`/clients/districts/reviews/${reviewId}/${type}/validate`, itemreviewData).then(response => {
    console.log('response.data :')
    console.log(response.data)
    commit('setItemReviewsErrors', 'teststring')
  })
}

The setItemReviewsErrors mutation in the vuex store doesn't do much with the response yet :

export const setItemReviewsErrors = (state, data) => {
  console.log('*** setItemReviewsErrors() called, data:')
  console.log(data)
}

However, the issue arises when the following error occurs :

Uncaught (in promise) TypeError: Converting circular structure to JSON
    at JSON.stringify (<anonymous>)
    at eval (vuex-persistedstate.es.js?0e44:1)
    at eval (vuex-persistedstate.es.js?0e44:1)
    at eval (vuex.esm.js?2f62:392)
    at Array.forEach (<anonymous>)
    at Store.commit (vuex.esm.js?2f62:392)
    at Store.boundCommit [as commit] (vuex.esm.js?2f62:335)
    at local.commit (vuex.esm.js?2f62:651)
    at eval (itemreview_actions.js?0d87:62)

Further investigation reveals that this problem may be related to the vuex-persistedstate plugin being used. Others have faced similar issues as well :

Unfortunately, the developer seems to have closed the tickets without a solution. If anyone has any insights on resolving this issue without removing the persistence plugin, please share.

Answer №1

For an alternative solution, check out the library vuex-persist, which tackles this issue directly

In case you encounter circular structures within your state

let x = { a: 10 }  
x.x = x  
x.x === x.x.x // true  
x.x.x.a === x.x.x.x.a //true  

Using JSON.parse() and JSON.stringify() won't resolve the problem.

You'll have to install circular-json

npm install circular-json

Furthermore, when setting up the store, ensure to include the supportCircular flag

new VuexPersistence({
  supportCircular: true,
  ...
})

It's worth noting that having a circular reference in your state could lead to other issues, especially if a reactive property triggers another call to the same mutation. In such cases, you may encounter a Maximum call stack size exceeded error promptly.

Refer to the comment made by Linus Borg regarding this code snippet

mutations:
saveVideoComment(state, {id, text, videoId}) {
    let comment = {
        id: id,
        videoId: videoId,
        text: text,
        inlineUserVideo: state.userVideos[userVideoId]
    };
    Vue.set(state.videoComments, id, comment);
    state.videos[videoId].comments.push(id);
    state.videos[videoId].inlineComments.push(comment);
}

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

Retrieve the Firepad textarea element or the current character being typed

I'm looking to add hashtag functionality to Firepad using jQuery. Is there a way to access the textarea element or the character being typed in the Firepad editor? For example, can I trigger an event when typing '#'? I attempted to use the ...

Node.js Friendship NetworkIncorporating Friendships in Node

Currently, I have successfully set up a real-time chat application using node.js and socket.io. My next goal is to allow users to create accounts, search for other users by username, and send friend requests to start chatting. I have tried searching onlin ...

Obtain JSON data response in PHP with the help of jQuery

Below is the code I am using to make an AJAX call and retrieve data from another PHP file: $.post('<?php echo get_site_url(); ?>/ajax-script/',{pickup:pickup,dropoff:dropoff,km:km}, function(data){ $('#fare'). ...

Should a React application perform a complete refresh when a file is reloaded?

Recently, I delved into the world of React and learned about one of its key benefits: updating only the necessary DOM elements. However, as I began building an app from scratch, I encountered a situation where every time I saved the .js file, it resulted ...

What is the best way to merge setInterval with mouseenter events?

I have successfully implemented code that refreshes a div using ajax. However, I am looking to add functionality so that the div only refreshes every 30 seconds when the tab is active. It seems that setInterval currently refreshes the div regardless of tab ...

Guide to saving an http response as a file and automatically retrying on a 503 error

When it comes to piping the response of an http request to a file, the process is pretty straightforward: http.get(url, function (res) { var file = fs.createWriteStream(filename) res.pipe(file) file.on('finish', function () { file.clos ...

Ways to efficiently manage session control without repeating it in each route

I'm currently working on a Node.js application using express. I've been checking the session in every route, but now I'm looking for a way to separate this check from my routes. Any suggestions? Below is an example of one of my routes: app ...

Importing XML data into a JavaScript variable using jQuery without displaying an alert message

Despite previously asking questions about loading XML into a JS variable, I haven't found a satisfactory solution. In my script, I declare a variable before making an ajax request and then assign the result to that variable. However, this only seems t ...

When implementing helmetJS into my project, I noticed that Font Awesome was displaying white squares

Initially, I created an application that utilized this code in the HTML and incorporated classes with Font Awesome icons, which functioned effectively. <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.1/css/all.css&q ...

"Strategies for effectively utilizing the .find method to locate specific users within a database

I'm currently working on developing a User Authentication system, but I've hit a roadblock when it comes to verifying users. Specifically, I'm struggling with understanding how to iterate through all of my users in order to filter out their ...

What is the method to activate map dragging in Leaflet only while the spacebar is pressed?

When using Leaflet maps, the default behavior is to drag the view around by only clicking the mouse. However, I am interested in enabling dragging with the mouse only if the spacebar is pressed as well. I would like to reserve mouse dragging without the sp ...

Using a PHP variable to trigger the jQuery .show() function

I'm attempting to trigger jQuery .show() events based on PHP variables. Below is my PHP code (retrieved from a form submission on another page): $last_pic_displayed = trim($_POST["last_pic_displayed"]); if (strlen($last_pic_displayed) <= ...

What is the best way to modify the state of an array of objects by applying a filter in Vue 3?

I am currently facing an issue with a component that is listening for an emit and then attempting to filter out a user with a specific userId from the users state. The challenge lies in the fact that assigning filteredUsers to users does not appear to be ...

Retrieve the link's "href" attribute and its text if they match the specified text

Is there a way to extract the href link and text from a specific type of link? <a href="google.com">boom</a> I am looking to retrieve only the 'google.com' part and the text 'boom' Furthermore, how can I filter out other ...

Issue: Unable to locate the "es2015" preset in relation to the given directory

I encountered an issue while attempting to use babel. Error: Couldn't find preset "es2015" relative to directory webpack.config.js module.exports = { entry: './main.js', ourput: { path:'./', filename:&a ...

Shopify module is throwing an error stating that React is not defined

I wanted to create my first Shopify module, but I encountered an error in my application page on the shop while using React. Here is my index.js code: import {Page} from "@shopify/polaris"; import {ResourcePicker} from "@shopify/app-bridge- ...

Leveraging the power of React's callback ref in conjunction with a

I'm currently working on updating our Checkbox react component to support the indeterminate state while also making sure it properly forwards refs. The existing checkbox component already uses a callback ref internally to handle the indeterminate prop ...

Gain access to Google Analytics without the need for page consent by utilizing JavaScript

I am currently building a dashboard with Atlasboard. My goal is to retrieve Google analytics data such as page views, and I plan to run specific queries which can be found here. Is there a method to access my Google analytics data without the consent pag ...

What is the best approach for creating a test that can simulate and manage errors during JSON parsing in a Node.js

My approach to testing involves retrieving JSON data from a file and parsing it in my test.js file. The code snippet below demonstrates how I achieve this: var data; before(function(done) { data = JSON.parse(fs.readFileSync(process.cwd() + '/p ...

Can a software be created to capture search results from the internet?

Is it feasible to create a program that can extract online search results? I am specifically interested in retrieving data from Some of the data I need include application numbers, such as 9078871 and 10595401 Although there are CAPTCHAs present, I am w ...