Sending the response data from an API call to a Vue object

In the vue block below, I have successfully pushed my response data into the dateEvents return. Additionally, I am rendering events for a calendar package I am using. My goal is to map my response data to the events object where the name becomes the event title and the available_at corresponds to the event start.

To elaborate, the response data looks like this:

[name:"test one", available_at:"2019-09-25"][name:"test two", available_at:"2019-09-25"]
. Therefore, I want to take the response.data that is being pushed into my events array and use the name as the title and available_at as the start. While I am able to retrieve and display the dateEvents, I am unsure of how to format them in this manner for events.

export default {
  data() {
    return {
      dateEvents: [],
      events: [
        {
          title: 'test',
          start: '2019-08-17',
        },
        {
          title: 'another test',
          start: '2019-08-20',
        },
      ],
      config: {
        defaultView: 'month',
        editable: true,
        eventRender: function(event, element) {
          console.log(event)
        },
      },
    }
  },
  created() {
    this.fetchTasks()
  },
  methods: {
    fetchTasks() {
      axios
        .get('/dashboard/tasks')
        .then(response => {
          // handle success
          console.log(response.data)
          this.dateEvents = response.data
          this.events = response.data
        })
        .catch(function(error) {
          // handle error
          console.log(error)
        })
        .finally(function() {})
    },
  },
}

Answer №1

To match your scheme, it is recommended to create a new array with objects by following the code snippet provided below. The logic involves mapping through the response data and generating a new object in each iteration, where the object includes title as item.name and start as item.item.available_at.

.then((response) => {
  // handle success
  console.log(response.data);
  const events = response.data.map(item => {
    return {
      title: item.name,
      start: item.available_at
    };
  });

  this.dateEvents = events;
  this.events = events;
})

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

Loading JavaScript variable with pre-processed JavaScript information

I have been working on loading test data into a javascript object and then passing it to my heating timers. While I have managed to make it work by individually inserting the code into each timer, I am looking to optimize my code and enhance my understandi ...

Error encountered with the {1}+ possessive quantifier in a JavaScript regex pattern

As I delve into learning Javascript and Express.js simultaneously, I decided to experiment with regular expressions while making a get request. To familiarize myself with regular expressions, I referred to this chart (also shown below). Greedy Reluctant ...

Calculate the sum of elements with JavaScript

I am working with an array where each element is an object that also contains an array. My goal is to calculate the sum of all items in the nested arrays. Here is the approach I have attempted: function getSum(total, item) { return total + item; } v ...

Implementing a persistent header on a WordPress site with Beaver Builder

My website URL is: . I have chosen to use beaver builder for building and designing my website. I am in need of a fixed header that can display over the top of the header image. Here is the code snippet that I currently have: <div id="header">html ...

JavaScript - Setting Image IDs upon Page Load

I've encountered a challenge with assigning IDs to elements containing the "img" tag. I've attempted to find solutions from others facing similar issues, but none of them quite align with my own problem. I am fairly new to Javascript and suspect ...

During the testing of a Vue single file component with Jest, the prop being sent is found to be undefined

I am currently working on testing a Vue single file component that takes a prop as an input. However, I am encountering an issue when I try to mock the prop, which is an object. The problem arises in the HTML where the object values are utilized, resulting ...

What is the best method for adjusting the text size within a doughnut chart using react-chartjs-2?

Is there a way to adjust the text size within the doughnut chart using react-chartjs-2? I find that the center text appears too small. https://i.stack.imgur.com/QsI0V.png import React, {Fragment} from 'react'; import Chart from 'chart.js&a ...

I am facing errors while running npm run build in my Vue CLI project, however, npm run dev is running smoothly without

I am encountering an issue when running npm run build as it generates a series of errors, whereas npm run dev runs smoothly without any errors. I have attempted to resolve this by modifying the public path in webpack.config.js to ./dist, but unfortunately ...

Utilizing PHP to create an interactive website

As a novice PHP developer, I took to Google in search of tutorials on creating dynamic PHP websites. What I found was that many tutorials used the $_GET variable to manipulate URLs and make them appear like this: example.com/?page=home example.com/?page= ...

Unable to utilize Bower due to a node.js malfunction

Currently facing an issue while attempting to utilize bower for installing all necessary components for my website project. Each time I make an attempt, the following error presents itself: TypeError: Object #<Object> has no method 'toLowerCase ...

The functionality of right-clicking or context clicking in Internet Explorer 11 using Selenium WebDriver is experiencing issues

When attempting to open/select a context menu by right-clicking on an element on a page, I am encountering an issue. Despite using the Action class to execute the click operation, the contextClick() command seems to be performed at a different location on ...

The Django error known as MultiValueDictKeyError occurs when a key

I encountered a MultiValueDictKeyError while working in Django. The issue arises when trying to logout a user from my website using the following code: In HTML </li> <li class="nav-item mr-3"> ...

Invoking a Jquery Dialog

Every time I click on the button to display a message, I encounter an issue where one MessageBox appears as expected. However, when I open the Jquery Dialog for the second time, two MessageBoxes pop up and the same problem occurs with three MessageBoxes on ...

Collapsing tabs feature in Bootstrap 4

I am working on a project with Bootstrap 4 Tab. My goal is to initially hide all tab contents and then show them when the corresponding tab is clicked. I achieved this by removing the active class from the tab-pane div. However, I encountered an issue wher ...

challenges encountered when saving a getjson request as a variable

I am experiencing difficulties in retrieving a variable from a getJSON() request. The issue lies within the following three functions: function getPcLatitude() { // onchange var funcid = "get_postcode_latitude"; var postcode = parseInt($('#i ...

Ways to mandate adjusting an option in <select> tag

Using the code $('select').change(function(){alert('changed');});, I am able to trigger an alert every time the option is changed. However, I also need to trigger the alert when the default option, which is the first one in the list, is ...

Determining when a text area has selected text without constant checking

class MarkdownEditor extends React.Component { constructor(props) { super(props); this.timer = null; this.startIndex = null; this.endIndex = null; } componentDidMount() { this.timer = setInterval(() => { this.setSelectio ...

Can you explain the variance between the two state updates in React?

Currently enrolled in a React course where the instructor is diving into state updates. I'm struggling to grasp the internal differences between these two code snippets, provided below for reference: Snippet that updates state directly class Counter ...

Assign an id attribute in KineticJS once the ajax call is successful

I have implemented KineticJS into my MVC application. To retrieve data from the database, I am utilizing ajax calls to web services in the API controller. One of the APIs returns an id that I want to assign to the current Kinetic.Group id attribute upon s ...

Why Are My JavaScript GET Request Parameters Displaying as Strings Rather Than Numbers?

Currently, I am in the process of developing a REST API where one of the defined routes looks like this: router.get("/objects/:id?/:val1?/:val2?", getObject); Specifically, my request from Postman appears as follows: http://localhost:8000/objects?val1= ...