Refactor app.container to load current user.

This commit is contained in:
Patrick Fic
2019-12-09 19:49:43 -08:00
parent f919025159
commit 7de41f77ae
6 changed files with 122 additions and 39 deletions

View File

@@ -1,29 +1,115 @@
import React from "react";
import React, { Component } from "react";
import { Mutation, Query } from "react-apollo";
import { GET_CURRENT_USER, SET_CURRENT_USER } from "../graphql/local.queries";
import App from "./App";
import Spin from "../components/loading-spinner/loading-spinner.component";
export default () => {
return (
<Query query={GET_CURRENT_USER}>
{({ loading, error, data: { currentUser } }) => {
if (loading) return <Spin />;
if (error) return error.message;
return (
<Mutation mutation={SET_CURRENT_USER}>
{setCurrentUser => (
<App
currentUser={currentUser}
setCurrentUser={user => {
setCurrentUser({ variables: { user } });
}}
/>
)}
</Mutation>
);
}}
</Query>
);
};
import ApolloClient from "apollo-client";
import { InMemoryCache } from "apollo-cache-inmemory";
import { HttpLink } from "apollo-link-http";
import { setContext } from "apollo-link-context";
import { resolvers, typeDefs } from "../graphql/resolvers";
import apolloLogger from "apollo-link-logger";
import { ApolloLink } from "apollo-boost";
import { ApolloProvider } from "react-apollo";
import { persistCache } from "apollo-cache-persist";
import initialState from "../graphql/initial-state";
class AppContainer extends Component {
state = {
client: null,
loaded: false
};
async componentDidMount() {
const httpLink = new HttpLink({
uri: process.env.REACT_APP_GRAPHQL_ENDPOINT
});
const authLink = setContext((_, { headers }) => {
// get the authentication token from local storage if it exists
const token = localStorage.getItem("token");
// return the headers to the context so httpLink can read them
if (token) {
return {
headers: {
...headers,
authorization: token ? `Bearer ${token}` : ""
}
};
} else {
return { headers };
}
});
const middlewares = [];
if (process.env.NODE_ENV === "development") {
middlewares.push(apolloLogger);
}
middlewares.push(authLink.concat(httpLink));
const cache = new InMemoryCache({ addTypename: false });
const client = new ApolloClient({
link: ApolloLink.from(middlewares),
cache,
typeDefs,
resolvers
});
client.writeData({
data: {
...initialState
}
});
try {
// See above for additional options, including other storage providers.
await persistCache({
cache,
storage: window.localStorage
});
} catch (error) {
console.error("Error restoring Apollo cache", error);
}
this.setState({
client,
loaded: true
});
//Init local state.
}
render() {
const { client, loaded } = this.state;
if (!loaded) {
return <div>Loading...</div>;
}
return (
<ApolloProvider client={client}>
<Query query={GET_CURRENT_USER}>
{({ loading, error, data: { currentUser } }) => {
if (loading) return <Spin />;
if (error) return error.message;
return (
<Mutation mutation={SET_CURRENT_USER}>
{setCurrentUser => (
<App
currentUser={currentUser}
setCurrentUser={user => {
setCurrentUser({ variables: { user } });
}}
/>
)}
</Mutation>
);
}}
</Query>
</ApolloProvider>
);
}
}
export default AppContainer;

View File

@@ -74,6 +74,7 @@ class App extends React.Component {
}
render() {
console.log("this.props.currentUser", this.props.currentUser);
return (
<div>
<Switch>

View File

@@ -7,25 +7,12 @@ import * as serviceWorker from "./serviceWorker";
import "./index.css";
import AppContainer from "./App/App.container";
import { ApolloProvider } from "react-apollo";
import { client } from "./graphql/client";
import initialState from "./graphql/initial-state";
require("dotenv").config();
//Init local state.
client.writeData({
data: {
...initialState
}
});
ReactDOM.render(
<ApolloProvider client={client}>
<BrowserRouter>
<AppContainer />
</BrowserRouter>
</ApolloProvider>,
<BrowserRouter>
<AppContainer />
</BrowserRouter>,
document.getElementById("root")
);

View File

@@ -11,6 +11,9 @@ export default function Manage({match}) {
return (
<div>
<Route exact path={`${match.path}`} component={ManageShopContainer}/>
<Route exact path={`${match.path}/jobs`} component={ManageShopContainer}/>
<Route exact path={`${match.path}/jobs/:jobId`} component={ManageShopContainer}/>
</div>
)
}

View File

@@ -15,6 +15,7 @@
"heroku-postbuild": "cd client && npm install && npm install --only=dev --no-shrinkwrap && npm run build"
},
"dependencies": {
"apollo-cache-persist": "^0.1.1",
"body-parser": "^1.18.3",
"compression": "1.7.4",
"cors": "2.8.5",

View File

@@ -272,6 +272,11 @@ anymatch@~3.1.1:
normalize-path "^3.0.0"
picomatch "^2.0.4"
apollo-cache-persist@^0.1.1:
version "0.1.1"
resolved "https://registry.yarnpkg.com/apollo-cache-persist/-/apollo-cache-persist-0.1.1.tgz#e6cfe1983b998982a679aaf05241d3ed395edb1e"
integrity sha512-/7GAyblPR169ryW3ugbtHqiU0UGkhIt10NeaO2gn2ClxjLHF/nIkJD5mx/0OCF2vLNbbnzLZVDeIO1pf72TrEA==
archiver-utils@^2.1.0:
version "2.1.0"
resolved "https://registry.yarnpkg.com/archiver-utils/-/archiver-utils-2.1.0.tgz#e8a460e94b693c3e3da182a098ca6285ba9249e2"