How to get data from JSON with Axios?

If you've received text instead of JSON,just like I did,

With async/await, it's simply,

let results = await axios.get("http://localhost:3004/paymentReceipts")
try {
  let response = JSON.parse(results.request.response)  
  dispatch({ type: Actions.RECEIVE_DATA, payload: response })
} catch(err) {
  dispatch({type: Actions.FETCH_DATA_ERROR, payload: err})
}

To access a single attribute within your json-response you can simply do:

response.data.<attribute>

e.g.:

   axios.get("http://localhost:3004/paymentReceipts")
  .then((response) => {
    dispatch({ type: Actions.RECEIVE_DATA, payload: response.data, id: response.data.id }) //Change
  }).catch((err) => {
    dispatch({type: Actions.FETCH_DATA_ERROR, payload: err})
  })

Depending on the structure of your json and how it's formatted (e.g. array of objects) you have to iterate through it.


You will get all your data into response.data.

axios.get("http://localhost:3004/paymentReceipts")
  .then((response) => {
    dispatch({ type: Actions.RECEIVE_DATA, payload: response.data }) //Change
  }).catch((err) => {
    dispatch({type: Actions.FETCH_DATA_ERROR, payload: err})
  })