Skip to content

Instantly share code, notes, and snippets.

@illuminatedspace
Created March 11, 2017 23:56
Show Gist options
  • Save illuminatedspace/5e78e7bc3e67a4a722bb15e0b0254b56 to your computer and use it in GitHub Desktop.
Save illuminatedspace/5e78e7bc3e67a4a722bb15e0b0254b56 to your computer and use it in GitHub Desktop.
Race Condition between Component render and Container Async Call
import React, { Component } from 'react'
import { connect } from 'react-redux'
import axios from 'axios'
// import { fetchNearby, fetchHere } from '../reducers/secret'
import Secrets from '../components/Secrets'
import Jokes from '../components/Jokes'
class SecretsContainer extends Component {
constructor (props) {
super(props)
this.state = {
latitude: 0.00,
longitude: 0.00,
secretsHere: [],
secretsNearby: 0,
currentSecret: {},
}
this.setCurrentSecret = this.setCurrentSecret.bind(this)
this.getCoordinates = this.getCoordinates.bind(this)
this.fetchNearby = this.fetchNearby.bind(this)
this.fetchHere = this.fetchHere.bind(this)
}
getCoordinates () {
return new Promise(function(resolve, reject) {
navigator.geolocation.getCurrentPosition(resolve, reject)
})
}
setCurrentSecret (event) {
this.setState({
currentSecret: this.event.target.id,
})
}
fetchNearby () {
axios.put('/api/secrets/nearby', {
latitude: this.state.latitude,
longitude: this.state.longitude
})
.then(results => {
console.log('SECRETS NEARBY',results.data)
return this.setState({
nearby: results.data,
})
})
.catch(console.error)
}
fetchHere () {
axios.put('/api/secrets/here', {
latitude: this.state.latitude,
longitude: this.state.longitude
})
.then(results => {
console.log('SECRETS HERE',results.data)
return this.setState({
here: results.data,
})
})
.catch(console.error)
}
// componentWillMount () {
// console.log('IN SECRETS WILL MOUNT')
// }
componentDidMount () {
this.getCoordinates()
.then((position) => {
return this.setState({
longitude: position.coords.latitude,
latitude: position.coords.longitude,
})
})
.then(() => {
this.fetchNearby()
})
.then(() => {
this.fetchHere()
})
.catch(console.error)
// this.fetchNearby()
// this.fetchHere()
}
render() {
console.log('RENDER HERE',this.state.secretsHere)
console.log('RENDER NEARBY',this.state.secretsNearby)
return (
<Jokes
setSecret={this.setCurrentSecret}
secretsHere={this.state.secretsHere}
secretsNearby={this.state.secretsNearby}
/>
)
}
}
const mapStateToProps = state => {
}
const mapDispatchToProps = (dispatch, ownProps) => ({
})
export default connect(
null,
mapDispatchToProps
)(SecretsContainer)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment