Search code examples
vue.jsaxiosvuex

Getting Axios response data from a response with an array


This is the response from my server

{"message":"Resource Created","payload": 
[{"id":"5d80270413452b6732fd5217","name":"asdf"}]}

I am trying to set the id to my state.

Currently trying this.

axios.post(`http://localhost:8081/companies`, company)
     .then(request => request.data.payload.id)
     .then(id => {
         commit('setCreatedCompanyID', id)
     })

I believe the error is with this line

.then(request => request.data.payload.id)

How can I get the first ID from the response array?


Solution

  • Use myArray[index] to access the index-th element of the myArray array. Such as:

    .then(request => request.data.payload[0].id)
    

    Demo:

    axios.get(`https://api.myjson.com/bins/rin05`)
      .then(request => request.data.payload[0].id)
      .then(console.log)
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    Check the console