Jereme
Jereme

Reputation: 525

How to set State after mapping over an array and object in react/JS?

I’ve got a patients array in state. If the patient.room matches roomStates.room then I would like to set the patient.roomStatus to be roomStates[key].name. My function is as follows but I can’t see why its not working.

Patient array

const patients = [
{name: "Jay”, room: "room01", roomStatus: ""}, 
{name: "Leo”, room: "room02", roomStatus: ""}, 
{name: "Jim", room: "room05", roomStatus: ""}
]
const  roomState = { 
room01: {type: "info", room: "room01", name: "Stopped"},
room02: {type: "normal",room: "room02", name: "InRoom"},
room05: {type: "normal", room: "room05",name: "InRoom"},
}
   handleRoomStateChange(roomStates) {

        Object.keys(roomStates).map((key) => {
            this.state.patients.map(patient => {

                if (patient.room === roomStates[key].room) {


                    this.setState({ ...patient, roomStatus: roomStates[key].name});
                }

            })

        });
    }

Upvotes: 0

Views: 54

Answers (1)

Clarity
Clarity

Reputation: 10873

Do not set state on every loop iteration, save the data into array and then set it once the loop is done executing:

handleRoomStateChange = roomStates => {
  const patients = Object.keys(roomStates).map(key => {
    return this.state.patients.map(patient => {
      if (patient.room === roomStates[key].room) {
        return {
          ...patient,
          roomStatus: roomStates[key].name
        };
      }
      return patient;
    });
  });

  this.setState({patients});
};

Edit: that actually returns a nested array, to get a proper data structure extra map can be avoided:

handleRoomStateChange = roomStates => {
  const patients = this.state.patients.map(patient => {
    const roomKey = Object.keys(roomStates).find(key => key === patient.room);
    return {
      ...patient,
      roomStatus: roomStates[roomKey].name
    }
  });
  this.setState({ patients });
}

Upvotes: 1

Related Questions