Created
September 4, 2018 08:29
-
-
Save PaulieScanlon/619684e34e4a122a08430ef6266c5d2a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as React from "react"; | |
import { FetcherIndicator } from "../FetcherIndicator"; | |
import { fetchType } from "../../utils/fetch"; | |
interface IProps { | |
fetchMethod: { | |
method: string; | |
query?: string; | |
}; | |
dataReducer(data: any): any; | |
renderComponent(data: any): React.ReactNode; | |
} | |
export interface IState { | |
isLoading: boolean; | |
data: any; | |
hasErrored: boolean; | |
} | |
export class Fetcher extends React.Component<IProps, IState> { | |
public _isMounted = false; | |
constructor(props: any) { | |
super(props); | |
this.state = { | |
isLoading: true, | |
data: null, | |
hasErrored: false | |
}; | |
} | |
componentDidMount() { | |
// @TODO this _isMounted hack is gross.. works though :-) | |
this._isMounted = true; | |
const { method, query } = this.props.fetchMethod; | |
const dataFetch = (fetchType as any)[method](query); | |
dataFetch.then((res: any) => { | |
if (this._isMounted === true) { | |
this.setState({ | |
isLoading: res.isLoading, | |
data: res.data ? this.props.dataReducer(res.data) : null, | |
hasErrored: res.hasErrored | |
}); | |
} | |
}); | |
} | |
componentWillUnmount() { | |
this._isMounted = false; | |
} | |
render() { | |
const { isLoading, data, hasErrored } = this.state; | |
const { renderComponent } = this.props; | |
if (isLoading) { | |
return <FetcherIndicator variant="loading" />; | |
} | |
return hasErrored ? ( | |
<FetcherIndicator variant="error" /> | |
) : ( | |
renderComponent(data) | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment