Skip to content

Instantly share code, notes, and snippets.

@danawoodman
Last active July 3, 2018 05:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save danawoodman/dfb900623a254cd26f5682fc83596032 to your computer and use it in GitHub Desktop.
Save danawoodman/dfb900623a254cd26f5682fc83596032 to your computer and use it in GitHub Desktop.
Basic React Router setup with Async
import React, { Component } from "react";
import logo from "./logo.svg";
import "./App.css";
import { BrowserRouter as Router, Route, Link } from "react-router-dom";
const COMPANIES = [
{
id: 1,
name: "Foo",
accounts: [{ id: 4, name: "SubAccount", accounts: [] }]
},
{ id: 2, name: "bar", accounts: [] },
{ id: 3, name: "Baz", accounts: [] },
{ id: 4, name: "SubAccount", accounts: [] }
];
function AccountPage({ company, error, loading }) {
if (error) return <h1>{error}</h1>;
if (loading) return <h1>Fetching company data...</h1>;
if (!company) return <h1>No Company</h1>;
return (
<div>
<h1>{company.name}</h1>
<p>{company.desc}</p>
{company.accounts.map((account, key) => (
<p key={key}>
<Link to={`/${account.id}`}>{account.name}</Link>
</p>
))}
</div>
);
}
class Child extends React.Component {
state = { company: null, error: null, loading: false };
componentWillMount() {
this.fetch();
}
componentDidUpdate(prevProps) {
const newId = this.props.match.params.id;
const oldId = prevProps.match.params.id;
if (newId !== oldId) this.fetch();
}
fetch() {
this.setState({ error: null, loading: true });
const id = Number(this.props.match.params.id);
setTimeout(() => {
const company = COMPANIES.find(c => c.id === id);
this.setState({ company, loading: false });
}, 300);
// axios
// .get(`/api/companies/${id}`)
// .then(company => this.setState({ company }))
// .catch(error => this.setState({ error: error.message }))
// .finally(() => this.setState({ loading: false }));
}
render() {
return <AccountPage {...this.state} />;
}
}
function Home() {
return <h1>Home</h1>;
}
class App extends Component {
render() {
return (
<Router>
<div>
<Route path="/:id" component={Child} />
<Route exact path="/" component={Home} />
</div>
</Router>
);
}
}
export default App;
const COMPANIES = [
{
id: 1,
name: "Foo",
accounts: [{ id: 4, name: "SubAccount", accounts: [] }]
},
{ id: 2, name: "bar", accounts: [] },
{ id: 3, name: "Baz", accounts: [] },
{ id: 4, name: "SubAccount", accounts: [] }
];
app.get('/api/companies/:id', (req, res) => {
const id = req.params.id
const company = COMPANIES.find(c => c.id === id);
res.json(company)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment