Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pushing To React State Array

How can I write this better , I want to do it with setState instead of this.state.floors.push as I know that is bad practice but I couldnt figure it out. Im using react native.

FloorAPI.getFloorsByBuildingID(this.state.buildingID).then((response) => response.d.data.map((value) => {
  console.log(value.floorName)
  this.state.floors.push({value: value.floorName})
}))
like image 594
user3637804 Avatar asked Sep 06 '18 14:09

user3637804


2 Answers

// Create a new array based on current state:
let floors = [...this.state.floors];

// Add item to it
floors.push({ value: floorName });

// Set state
this.setState({ floors });
like image 190
imjared Avatar answered Oct 05 '22 13:10

imjared


For now, the best possible and simplest way is

  this.setState(previousState => ({
      floors: [...previousState.floors, {"value": value.floorName}]
  }));
like image 20
Hemadri Dasari Avatar answered Oct 05 '22 11:10

Hemadri Dasari