Pushing To React State Array

Viewed 54562

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})
}))
9 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 });

In hooks form u may use

setState((prevVals) => [...prevVals,newVals])

For now, the best possible and simplest way is

  this.setState(previousState => ({
      floors: [...previousState.floors, {"value": value.floorName}]
  }));
FloorAPI.getFloorsByBuildingID(this.state.buildingID).then((response) => { 
  // get current floors
  const { floors } = this.state;

  // get new floors after api request
  const newfloors = response.d.data.map((value) => ({value: value.floorName}))

  // set the new state by combining both arrays
  this.setState({ floors: [...floors, ...newfloors] });
})

You can use

this.setState({floors: [{value: value.floorName}]}); 

in order to use set state.

You can make a new variable and push to the variable then set the state after the map is complete

var tempArray = []

FloorAPI.getFloorsByBuildingID(this.state.buildingID).then((response) => response.d.data.map((value) => {
  tempArray.push({value: value.floorName})
}))

this.setState({floors: tempArray})
const { floors } = this.state;

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

// Set state
this.setState({ floors });

I tried a lot but what worked for me was .concat() function

import react,{useState} from 'react'

const [files,setFiles] = useState([]);

function addUp(acceptedFiles){
 // the code below adds up to the state, using the args
 setFiles((prev) => {
   return prev.concat(acceptedFiles);
 }); 
}

return <div> </div>

You can always use the previous state.

setState((prevState)=>({
   floors: prevState.floors.push({...})
});

Thats a nice way to avoid directly changing the state. Another way would be to do the following:

var newState=[...this.state.floors];
newState.push({...});

setState(()=>({
  floors: newState
)}
Related