Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting Axios response data from a response with an array

Tags:

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?

like image 494
jmacnc Avatar asked Sep 17 '19 00:09

jmacnc


1 Answers

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
like image 99
acdcjunior Avatar answered Oct 08 '22 17:10

acdcjunior