Reputation: 1258
I have been learning to react, earlier i have been just calling api in componentDidMount with axios it was working fine.
Now,this task was without getting data from api, therefore i as usual called setState in componentDidMOunt but since setState is async, it wasn't updated, when i need it.
I want to know how should i write this, in order to mitigate this issue. Here is a simple class code.
import React from 'react'
import CarCapacity from '../Components/TextBox/CarCapacity'
import randomHelper from '../Helper/randomCars'
import Row from 'react-bootstrap/Row'
class Parking extends React.Component{
state={
inText:null,
cars:100,
carDetails:[],
remainingSlots:[]
}
numberOfcars=(event)=>{
this.setState({inText:event.target.value})
}
updateFunc = ()=>{
var details = randomHelper(this.state.cars)
//setState is async therefore using a callBack to check if the state has been updated
this.setState({carDetails:{...details}},function(){
console.log(this.state.carDetails)
})
}
componentDidMount(){
this.updateFunc()
}
componentDidUpdate(prevProps, prevState){
if(prevState.cars!==this.state.cars){
this.updateFunc()
}
}
setToCars=()=>{
var st= this.state.inText;
if(this.state.inText==null||st.trim()===""){
alert("Cars cant be null")
}
else if(Number.isNaN(Number(this.state.inText))){
alert("Enter a number")
}
else{
this.setState({cars:this.state.inText})
}
}
render(){
console.log(this.state.carDetails)
var carParkingFormation = this.state.carDetails.map((data, index)=>{
var isCarParked = data.carNumber!==null? data.carNumber: "Not parked"
var color = data.carColor!==null? data.carColor:" "
var pos = data.carPosition
return(
<>
<Col md={4}>
<span>{isCarParked}</span>
<span>{color}</span>
<span>{pos}</span>
</Col>
</>
)
})
return(
<>
<CarCapacity carCapacity={this.numberOfcars} genCars={this.setToCars}/>
<p>{this.state.cars}</p>
<Row>
{carParkingFormation}
</Row>
</>
)
}
}
export default Parking
Here, in this carParkingFormation this.state.carDetail is null as setState beig async, so, how can i ensure that it runs properly as the way expected
Upvotes: 0
Views: 52
Reputation: 4315
Your carDetails
is an array and you are setting it as an object in updateFunc
so in that case the map in render will not work on object. Try changing it to below:
this.setState({carDetails:[...details]},function(){
console.log(this.state.carDetails)
})
Upvotes: 2