Created
January 6, 2019 07:20
-
-
Save jakewilson801/737df01a029861072e76c07a890b9b4e to your computer and use it in GitHub Desktop.
Firebase render props
This file contains hidden or 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 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