After pushing submit button I use fetch button to get information about git user from git api. After information is fetched I write it to database and then setState with userIsFetched: true
and then conditionally render components.
The problem is that after I change state userIsFetched: true
I see for a second my <Chat />
component, but then I see <Signup />
component. In the console I see that the state is erased. If I use xmlhttprequest then it works fine. Why this is happening?
var database = firebase.database();
/*function readData() {
return firebase.database().ref('users/0dc2074d-f7db-4746-91bd-d6e61498b666').once('value')
.then((data)=>data.val())
}*/
class Chat extends React.Component {
render() {
return (<div>
<div className="row">
<div className="col">header</div>
</div>
<div className="row" >
<div className="col-10">one</div>
<div className="col-2">two</div>
</div>
<div className="row">
<div className="col">footer</div>
</div>
</div>)
}
}
class SignIn extends React.Component {
constructor(props) {
super(props);
this.state = {
signLogin: ''
}
this.handleSubmit = this.handleSubmit.bind(this);
this.handleChange = this.handleChange.bind(this);
}
handleSubmit() {
this.props.handleSignInSubmit(this.state.signLogin);
}
handleChange(event) {
this.setState({
signLogin: event.target.value
})
}
render() {
return (<div>
<form className="form-signin" onSubmit={this.handleSubmit}>
<h2 className="form-signin-heading">Please sign in</h2>
<br/>
<label className="sr-only">Name</label>
<input type="text" className="form-control" placeholder="Name" required="" autoFocus="" onChange={this.handleChange} value={this.state.value}/>
<br/>
<button className="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
</form>
</div>)
}
}
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
}
this.handleSignInSubmit = this.handleSignInSubmit.bind(this);
}
handleSignInSubmit(signLogin) {
fetch(`https://api.github.com/users/${signLogin}`)
.then((response)=>response.json())
.then((user)=>this.writeUserData(uuidv4(), user.name, user.avatar_url))
.then(()=>this.setState({userIsFetched: true}))
.catch( alert );
}
writeUserData(userId, userName, userAvatarUrl) {
firebase.database().ref('users/' + userId)
.set({
userName: userName,
userAvatarUrl : userAvatarUrl
});
}
render() {
console.log(this.state)
return this.state.userIsFetched ? <Chat /> : <SignIn handleSignInSubmit={this.handleSignInSubmit}/>
}
}
ReactDOM.render(<App/>, document.getElementById("root"));
Here is the working example: https://codepen.io/RinatRezyapov/pen/WEEqJW
try enter RinatRezyapov and click Submit.