In this class component, im trying to make a request inside componentDidMount and then setting the state after the request.
After the state (here, this.state.locationElements and this.state.toUpdate) is set, im trying to access one of the this.state.locationElements's element's props and setting this.state.currentCoordinates with it.
The problem is that none of the locationElements are displayed on initial render and are only displayed once i make a change in my code, save it and turn to the localhost.
class AddressInput extends React.Component {
constructor(props) {
super(props);
this.newAddress = createRef();
this.state={
currentCoordinates: {},
locationElements: [],
inComponent: false,
checkedIndex: 0,
isAddressSet: false,
toUpdate: false
}
}
componentDidMount(){
this.getAllAddresses()
}
componentDidUpdate(){
console.log(this.state.locationElements, this.state.toUpdate)
if (this.state.locationElements.length!==0 && this.state.toUpdate){
console.log('in update')
this.setState({
currentCoordinates: this.state.locationElements[this.state.checkedIndex].props.coordinates
})
if (this.state.currentCoordinates){
console.log(this.state.currentCoordinates)
this.setState({toUpdate: false})
}
}
}
async getAllAddresses(){
if (this.props.email){
await axios.get(`/api/users/${this.props.email}`)
.then((res) => {
this.setState({locationElements: []})
const data = res.data.addresses
const dummy = []
for (let i = 0; i < data.length; i++) {
const element = data[i];
dummy.push((
<Form.Check type='radio'
value={i}
label={element.address}
coordinates={element.coords}
checked={this.state.checkedIndex === i}
onChange={(e) => {
console.log(e.target, this.state.checkedIndex)
this.setState({checkedIndex: e.target.value})
}}
/>
))
}
this.setState({
locationElements: dummy,
toUpdate: true
})
})
}
}
render() {
return (
<div>
<Form onSubmit={(e) => {
e.preventDefault()
//AfterLocationSetOrSubmit()
}}>
<Form.Group className='mb-3'>
<Form.Label>Add a new address</Form.Label>
<LocationSearchInput ref={this.newAddress} />
</Form.Group>
<Form.Group className='mb-3'>
<Form.Label>Select from previous addresses:</Form.Label>
{this.state.locationElements}
</Form.Group>
<Button type='submit'>Set</Button>
</Form>
</div>
);
}
}