Making changes to the retrieved properties using Apollo GraphQL within a Vue.js environment

I'm trying to utilize the Moment javascript library to format a date that I retrieve through Apollo-GraphQL. My setup involves VueJS Apollo on the client side for executing graphQL queries like this:

import { ALL_EVENTS } from '../constants/graphql.js'
import Event from './Event'
import moment from 'moment'

export default {
  name: 'EventList',
  data: () => ({
      events: [],
      loading: 0
    }),
  apollo: {
    events: ALL_EVENTS
  },
  components: {
    Event
  },

The response from apollo middleware provides an array of objects with properties such as id, name, startDate (in UTC format), and endDate (also in UTC format).

When attempting to create a computed property in VueJS using the list of objects from Apollo, I encounter a read-only error even though it appears that I am creating a new object:

  computed: {
    eventsFormatted: function () {
      var out = this.events
      for (var i in out) {
        out[i].startDate = moment(out[i].startDate)
        out[i].endDate = moment(out[i].endDate)
      }
      return out
    }
  }

What steps should I take to generate a copy of the array that is editable?

Answer №1

After assigning this.events to a new variable out, both variables now refer to the same array of objects.

If this.events is immutable, you will need to duplicate the array and duplicate each object within it if they are also immutable.

Below is an example that demonstrates using the spread operator to copy both the array and the objects:

computed: {
  eventsFormatted() {
    let out = [...this.events];
    for (let i in out) {
      let item = {...out[i]};
      item.startDate = moment(item.startDate);
      item.endDate = moment(item.endDate);
      out[i] = item;
    }
    return out;
  }
}

The code snippet above creates a shallow copy of each object in the array. For deep copying due to the complexity of this.events, refer to this post.

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

CoffeeScript is failing to run the code

I'm attempting to use a click function to alter the CSS code and then run a function. Here is my current code: ready: -> $("#titleDD").click -> $("#titleDD").css('text-decoration', 'underline'); $("#catDD").css( ...

Display successive slidedown notifications consecutively

I want to implement a feature that shows slide down alerts using angularjs. Here is the code I have written: function LoginController($scope, $timeout) { $scope.alerts = [{ name: "Alert 01 something something" }, { name: &qu ...

What is the best way to retrigger an ajax request in jQuery after it encounters an error?

In my JavaScript code, I have an AJAX request that communicates with a Rails controller to send data. If the controller detects duplicate information already in the database, it returns an 'Unprocessable Entity' error. I am looking to implement ...

Retrieve the canvas coordinates for the images starting at lx and ending at rx on the x-axis, and

Currently, I am working on a project where I need to implement a drag and drop feature for an image within a PDF document. The goal is to retrieve the coordinates of the dragged image and use them later for document signing. The situation I am dealing wit ...

Guide to modifying the root directory when deploying a Typescript cloud function from a monorepo using cloud build

Within my monorepo, I have a folder containing Typescript cloud functions that I want to deploy using GCP cloud build. Unfortunately, it appears that cloud build is unable to locate the package.json file within this specific folder. It seems to be expectin ...

Updating the parent's reference from a child component in Vue 3

In one of my child components, I have a component named Navbar that includes an option for logging out. <a @click="(event) => {event.preventDefault();}"> Logout </a> This Navbar component has been imported into my parent compon ...

Vue.js v-cloak lifecycle method

Currently, I am working on a project where I have styled v-cloak with display: none, and it is decorating the body. As a result, everything remains hidden until the Vue instance is ready. I have created a component that inserts a chart (using highcharts). ...

Error encountered in React and Redux: Unable to read properties of undefined (specifically 'region')

Whenever a user clicks on edit, I am fetching data (an object) into a redux state and displaying it in a textarea. Here is the code snippet: const regionData = useSelector((state) => state.myReducer.userDetailList.region); The problem arises when this ...

transform JSON structure into an array

Is it possible to convert an interface class and JSON file into a list or array in order to work on it? For example, extracting the Racename from each object in the JSON file and storing it in a list/array. Here is the interface structure: interface IRunn ...

What is the best way to hide or show child elements within dynamically added components that are created using v-for loop in Vue.js

In this code snippet, there is a header text and some child elements. The goal here is to have the child elements toggle (hide/unhide) when the header is clicked. For instance, clicking on Spanish01 should hide all its children, and clicking it again shoul ...

Issue with Vuexfire {serialize} option causing improper formatting of arrays

I am attempting to aggregate all the Firestore document Ids when querying a collection. While I can successfully query all collections within an instance, I am struggling to correlate their document Ids with the collection arrays. The following code allow ...

What is the best way to handle waiting for an HTTP request to complete from a separate component?

https://i.sstatic.net/q4XYB.png An issue arises when calling the GetData function from a component's controller too early. I would like it to wait for the identification process to complete before triggering. During page loading, there is a server c ...

Leverage Node.js/Express backend objects within frontend JavaScript

I'm new to programming and feeling a bit lost. I've been struggling to find a solution for my issue despite spending a lot of time searching. Currently, I am working on coding a prototype for a simple web app using Node.js, Express, MongoDB, and ...

Creating a JSON object from two arrays is a simple process

Consider the following two arrays: let values = ["52", "71", "3", "45", "20", "12", "634", "21"]; let names = ["apple", "orange", "strawberry", &q ...

Does anyone have tips on how to upload images to MongoDB using React?

Currently, I am working on a project that requires an image upload feature for users. These images need to be stored in MongoDB so that they can be viewed by the user later on. Can anyone offer assistance with this? I have successfully configured my datab ...

CORS headers not functioning as expected for Access-Control-Allow-Origin

Can someone help me figure out how to add Access-Control-Allow-Origin: 'http://localhost:8080' in Node.js and Express.js? I keep getting this CORS error: Access to XMLHttpRequest at http://localhost:3000 from origin 'http://localhost:8080&ap ...

AngularJS is not responding to a 400 bad request

Despite my efforts to find solutions on Google and Stack Overflow for similar or identical issues, as a newcomer, none of them have provided me with any insight on how to resolve the issues in my code. Here is the script I am working with: $http.post(&ap ...

Methods for passing JavaScript variables to PHP

I have encountered this problem on Stack Overflow before, but I couldn't find a solution that worked for me. I am using Codeigniter and have a form where users can rate a product. What I need to achieve is to insert the user's rating into the dat ...

Solving Issues with URL Parameters and AJAX

My JSP page has a JavaScript function called loadData() that is triggered when the page loads. This function makes an AJAX request to a servlet in order to retrieve data and return the necessary HTML content to display on the page. I am trying to call thi ...

I've been waiting forever for Product.find() to return some results, but it seems to

I have been encountering an issue where my code is supposed to return an empty object of a product but instead it just keeps loading forever. I have thoroughly checked through the code and explored every possible scenario where an error could be occurring, ...