Skip to content

Instantly share code, notes, and snippets.

@jakewilson801
Created January 6, 2019 07:20
Show Gist options
  • Save jakewilson801/737df01a029861072e76c07a890b9b4e to your computer and use it in GitHub Desktop.
Save jakewilson801/737df01a029861072e76c07a890b9b4e to your computer and use it in GitHub Desktop.
Firebase render props
import HttpsCallable = firebase.functions.HttpsCallable;
import HttpsCallableResult = firebase.functions.HttpsCallableResult;
import { PureComponent, ReactElement } from 'react';
interface FireProps<T, V> {
callable: HttpsCallable;
initalData: T;
processData?: (result: HttpsCallableResult) => T;
dataToSend?: V;
render: (state: FireState<T>) => ReactElement<any>;
}
interface FireState<T> {
data: T;
didError: boolean;
isLoading: boolean;
}
class Fire<T, V> extends PureComponent<FireProps<T, V>, FireState<T>> {
constructor(props) {
super(props);
this.state = {
data: props.initalData,
didError: false,
isLoading: true,
};
}
async componentDidMount() {
this.callFirebase();
}
callFirebase = async () => {
const { processData, callable, dataToSend } = this.props;
this.setState({ isLoading: true }, async () => {
try {
let result;
if (dataToSend) {
result = await callable();
} else {
result = await callable(dataToSend);
}
if (processData) {
this.setState({ data: processData(result) });
} else {
this.setState({ data: result.data });
}
} catch (e) {
this.setState({ didError: true });
}
this.setState({ isLoading: false });
});
};
render() {
return this.props.render(this.state);
}
}
export default Fire;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment