richardoey
richardoey

Reputation: 39

Object Destructuring from API in Vue3

I want to put the data from API to Vue state. What is the quick approach to do this?

getProjectData(id) {
      axios.get(`/api/project/${id}`).then((res) => {
        console.log(res)
        /* I don't want to manually assign the value one by one (since the name is the same, there should be a quick way */
        this.formState.name = res.data.projects.name
        this.formState.stage = res.data.projects.stage
        this.formState.status = res.data.projects.status
        this.formState.description = res.data.projects.description
        this.formState.stations = res.data.projects.stations
      });
    },

Upvotes: 1

Views: 234

Answers (1)

Tushar Shahi
Tushar Shahi

Reputation: 20626

You can use spread operator to achieve it:

this.formState = {...res.data.projects}

To point out, these properties are copied shallowly. If a property value is an object, any modification made to it will reflect in the res.data.projects object.

Upvotes: 1

Related Questions