Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Better loading & ✨hooks ✨ #1335

Closed
wants to merge 6 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -114,8 +114,8 @@
"nanoid": "^2.0.0",
"path-to-regexp": "^2.4.0",
"prop-types": "^15.6.2",
"react": "^16.6.3",
"react-dom": "^16.6.3",
"react": "^16.8.2",
"react-dom": "^16.8.2",
"react-helmet": "^5.2.0",
"react-router-config": "^4.4.0-beta.6",
"react-router-dom": "^4.3.1",
Expand Down Expand Up @@ -158,7 +158,7 @@
"lighthouse-ci": "1.3.1",
"npm-run-all": "^4.1.5",
"prettier": "^1.15.0",
"react-test-renderer": "^16.6.3",
"react-test-renderer": "^16.8.2",
"snyk": "^1.129.0",
"start-server-webpack-plugin": "^2.2.5",
"stylelint": "^9.7.1",
Expand Down
103 changes: 46 additions & 57 deletions src/app/containers/App/App.jsx
Original file line number Diff line number Diff line change
@@ -1,68 +1,57 @@
/* eslint-disable */
/*
* © Jordan Tart https://github.com/jtart
* https://github.com/jtart/react-universal-app
*/
import { Component } from 'react';
import { useEffect, useState, useRef } from 'react';
import { renderRoutes } from 'react-router-config';
import { withRouter } from 'react-router-dom';

import loadInitialData from '../../routes/loadInitialData';

export class App extends Component {
constructor(props) {
super(props);
// number of ms before the loading screen is displayed.
const loadingScreenDelay = 1000;

this.state = {
data: this.props.initialData,
loading: false,
error: null,
loadInitialDataPromise: null,
};
}
const usePrevious = value => {
const ref = useRef();

async componentDidUpdate({ location: prevLocation }) {
if (this.props.location.pathname !== prevLocation.pathname) {
const initialData = loadInitialData(
this.props.location.pathname,
this.props.routes,
);
useEffect(
() => {
ref.current = value;
},
[value],
);

this.setState({
data: null,
loading: true,
error: null,
loadInitialDataPromise: initialData,
});
}
return ref.current || value;
};

if (this.state.loading) {
try {
const data = await this.state.loadInitialDataPromise;
this.setState({
data,
loading: false,
error: null,
loadInitialDataPromise: null,
});
} catch (error) {
this.setState({
data: null,
loading: false,
error,
loadInitialDataPromise: null,
});
}
}
}
const resetScroll = () => window.scrollTo(0, 0);

export const App = ({ initialData, location, routes }) => {
const [data, setData] = useState(initialData);
const [loading, setLoading] = useState(false);
const previousLocationPath = usePrevious(location.pathname);

const fetchData = async () => {
const timer = setTimeout(() => {
setLoading(true);
resetScroll();
}, loadingScreenDelay);

render() {
return renderRoutes(this.props.routes, {
data: this.state.data,
loading: this.state.loading,
error: this.state.error,
});
}
}
setData(await loadInitialData(location.pathname, routes));

clearTimeout(timer);
setLoading(false);
resetScroll();
};

useEffect(
() => {
if (previousLocationPath !== location.pathname) {
fetchData();
}
},
[location],
);

return renderRoutes(routes, {
data,
loading,
});
};

export default withRouter(App);
69 changes: 29 additions & 40 deletions src/app/containers/Article/index.jsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import React, { Fragment } from 'react';
import { bool, string, shape } from 'prop-types';
import { bool, shape } from 'prop-types';
import Helmet from 'react-helmet';
import HeaderContainer from '../Header';
import FooterContainer from '../Footer';
Expand All @@ -9,61 +9,50 @@ import { PlatformContextProvider } from '../../contexts/PlatformContext';
import GlobalStyle from '../../lib/globalStyles';
import ArticleMain from '../ArticleMain';
import ErrorMain from '../ErrorMain';
import nodeLogger from '../../helpers/logger.node';
import ConsentBanner from '../ConsentBanner';

const logger = nodeLogger(__filename);

/*
[1] This handles async data fetching, and a 'loading state', which we should look to handle more intelligently.
*/
const ArticleContainer = ({ loading, error, data }) => {
if (loading) return 'Loading...'; /* [1] */
if (error) {
logger.error(error);
return 'Something went wrong :(';
}
if (data) {
const { isAmp, data: articleData, service, status } = data;
const ArticleContainer = ({ loading, data }) => {
const { isAmp, data: articleData, service, status } = data;

return (
<Fragment>
<GlobalStyle />
<ServiceContextProvider service={service}>
<PlatformContextProvider platform={isAmp ? 'amp' : 'canonical'}>
<Helmet>
<link
rel="manifest"
href={`/${service}/articles/manifest.json`}
/>
</Helmet>
<ConsentBanner />
<HeaderContainer />
{status === 200 ? (
<ArticleMain articleData={articleData} />
) : (
<ErrorMain status={status} />
)}
<FooterContainer />
</PlatformContextProvider>
</ServiceContextProvider>
</Fragment>
);
}
const showLoading = loading;
const showArticle = !showLoading && status === 200 && articleData;
const showError = !showLoading && !showArticle;

return null;
return (
<Fragment>
<GlobalStyle />
<ServiceContextProvider service={service}>
<PlatformContextProvider platform={isAmp ? 'amp' : 'canonical'}>
<Helmet>
<link rel="manifest" href={`/${service}/articles/manifest.json`} />
</Helmet>
<ConsentBanner />
<HeaderContainer />
{showLoading && <h1>Loading...</h1>}
{showArticle && <ArticleMain articleData={articleData} />}
{showError && <ErrorMain status={status} />}
<FooterContainer />
</PlatformContextProvider>
</ServiceContextProvider>
</Fragment>
);
};

ArticleContainer.propTypes = {
loading: bool,
error: string,
data: shape(articlePropTypes),
};

ArticleContainer.defaultProps = {
loading: false,
error: null,
data: null,
data: {
isAmp: false,
service: 'news',
status: 500,
},
};

export default ArticleContainer;
2 changes: 1 addition & 1 deletion src/app/containers/ErrorMain/index.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ const ErrorMetadata = ({ locale, messaging, brandName, themeColor }) => {
);
};

const ErrorMain = ({ status }) => (
const ErrorMain = ({ status = 500 }) => (
<ServiceContextConsumer>
{({ brandName, locale, themeColor, translations }) => {
const messaging = translations.error[status] || translations.error[500];
Expand Down