-1

I have 2 get request which return details that corresponds to a patient.

First GET request returns patient’s details and encrypted patientId, which is used on the Second GET request to get the patient’s name. I need to save both the value of get request into an array in the state on patients: [{ }] but that patient on state shows empty with what I've tried.

const getUserConfig = await axios.get(`/room/room01/userconfig`);
const uuId = getUserConfig.data.room01.patientId;
console.log(uuid) // is the patientId

`Returned Data`

{
  "room01": {
    "conditions": [
      "Fever”, “Headache”
    ],
    "room": "room01",
    "patientId": "e1040efd-dwe6-4956-a4g5-2a6caa6318f9",
    "observationLevel": "1",
  }
}
The `Second GET request`

let getPatientName = await axios.get(`/patient/${uuId}/name`);
console.log(getPatientName.data); // is the patient name

How I'm trying to save on state but isn't working

  this.setState({
            patients: [
                {
                    patientName: getPatientName.data,
                    label:  patientData.data.room01.label, 
                    observationLevel: patientData.data.room01.observationLevel,
                }
            ]
        });


What the state should be looking like after both GET requests, and I would like to keep adding new patient to the next index in the array on the next GET request.

    this.state = {
            patients: [
{patientName: ‘string’, room: `room01`, observationLevel: `1`, …..}
]
        };

Jereme
  • 427
  • 7
  • 15
  • 1
    You keep getting the keys wrong. If that API reply is correct, it's `getUserConfig.data.room01.patientId` (not `.patient`). And your `setState` tries getting `room02.nhsNumber` from what you say is a string? And I don't see a `label` in the API response. –  Sep 11 '19 at 09:59
  • @ChrisG Hi apologies, I've made the corrections here, the code has correct keys and it doesn't setstate – Jereme Sep 11 '19 at 10:15
  • Possible duplicate of [Correct modification of state arrays in ReactJS](https://stackoverflow.com/questions/26253351/correct-modification-of-state-arrays-in-reactjs) –  Sep 11 '19 at 10:44

1 Answers1

0

I tried this and it worked: https://medium.com/@mirthfulnahid/using-the-spread-syntax-in-react-js-to-set-state-array-of-object-c47c631f64b0

const patientsArray = [{
            patientName: getPatientName.data,
            nhsNumber: patientData.data.room01.nhsNumber,
            label: patientData.data.room01.label,
            observationLevel: patientData.data.room01.observationLevel
        }];

        this.setState({
            patients: [...this.state.patients, ...patientsArray]})

Jereme
  • 427
  • 7
  • 15