Skip to content

Instantly share code, notes, and snippets.

@JacobKnaack JacobKnaack/app.js Secret
Last active Jun 14, 2019

Embed
What would you like to do?
Cosmic Messenger FINAL react app entry file
import React from 'react';
import { hydrate } from 'react-dom';
import ApolloClient from 'apollo-boost';
import { ApolloProvider } from 'react-apollo';
import { BrowserRouter, Route } from 'react-router-dom';
import { FiLogOut } from "react-icons/fi";
import axios from 'axios';
import { socket } from './lib/socket.js';
import LoginForm from './components/loginForm/loginForm.js';
import Chat from './components/chat/index.js';
import logo from '../public/logo.svg';
import './_app.scss';
const client = new ApolloClient({
uri: "https://graphql.cosmicjs.com/v1"
});
class App extends React.Component {
constructor() {
super()
this.state = {
user: {},
}
this.handleUser = this.handleUser.bind(this);
this.handleLogout = this.handleLogout.bind(this);
}
componentWillMount() {
if (localStorage.getItem('cosmic-messenger-user')) {
this.setState({ user: JSON.parse(localStorage.getItem('cosmic-messenger-user')) });
}
}
componentDidUpdate(prevProps, prevState) {
if (this.state.user.name && this.state.user !== prevState.user) {
localStorage.setItem('cosmic-messenger-user', JSON.stringify(this.state.user));
}
if (!this.state.user.name && this.state.user !== prevState.user) {
localStorage.removeItem('cosmic-messenger-user');
}
}
render() {
return (
<ApolloProvider client={client}>
<div className="app-container">
{this.state.user.name
? <header>
<img src={logo} />
<div>
<h3>{this.state.user.name} <span style={styles.appBttn} onClick={this.handleLogout}><FiLogOut /></span></h3>
</div>
</header>
: null
}
<div className="app-content">
<BrowserRouter>
<Route exact path='/'
render={props => (
<LoginForm
user={this.state.user}
handleUser={this.handleUser}
{...props}
/>
)}
/>
<Route path='/:user'
render={props => (
<Chat
handleLogout={this.handleLogout}
user={this.state.user}
{...props}
/>
)}
/>
</BrowserRouter>
</div>
</div>
</ApolloProvider>
);
}
handleUser(user) {
this.setState({ user })
}
handleLogout() {
axios.post(`${__API_URL__}/logout`, { username: this.state.user.name.replace(/\s+/g, '-').toLowerCase() })
.then(() => this.setState({ user: {} }, () => socket.emit('logout', {})))
.catch(err => console.error(err));
}
}
hydrate(
<App />,
document.getElementById('app')
);
module.hot.accept();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.