Skip to content

Instantly share code, notes, and snippets.

@mgenov
Created March 14, 2018 14:20
Show Gist options
  • Save mgenov/48107c4d4036b9e52dfd98cd468c1989 to your computer and use it in GitHub Desktop.
Save mgenov/48107c4d4036b9e52dfd98cd468c1989 to your computer and use it in GitHub Desktop.
AsyncCall & AsyncAction & AsyncButton
import React from "react";
import { render } from "react-dom";
import Hello from "./Hello";
const styles = {
fontFamily: "sans-serif",
textAlign: "center"
};
const timeoutAction = () => {
return new Promise(resolve => {
setTimeout(() => {
resolve({ name: "John" });
}, 1500);
});
};
class AsyncAction extends React.Component {
constructor(props) {
super(props);
this.state = {
loading: false,
data: null,
error: null
};
}
componentDidMount() {
this.onExecuteAction(this.props.onLoad);
}
onExecuteAction = action => {
if (action === undefined || action === null) {
return;
}
this.setState({ loading: true });
action()
.then(response => {
this.setState({ loading: false, data: response });
})
.catch(err => {
this.setState({ loading: false, error: err });
});
};
render() {
const { loading, data } = this.state;
const { onLoad } = this.props;
if (loading) {
return this.props.loading();
}
if (onLoad !== null && onLoad !== undefined) {
return this.props.render(loading, data);
}
return this.props.render(
() => this.onExecuteAction(this.props.action),
loading,
data
);
}
}
class AsyncCall extends React.Component {
render() {
return (
<AsyncAction
onLoad={this.props.action}
render={(loading, data) => this.props.render(loading, data)}
loading={() => this.props.loading()}
/>
);
}
}
class AsyncButton extends React.Component {
render() {
return (
<AsyncAction
action={() => this.props.onPress()}
render={(onCall, loading) => <button onClick={onCall}>Button</button>}
loading={() => <button>Loading...</button>}
/>
);
}
}
const App = () => (
<div style={styles}>
<AsyncCall
action={() => timeoutAction()}
loading={() => <div>Loading</div>}
render={(loading, data) => <div>Data: {JSON.stringify(data)}</div>}
/>
<AsyncButton onPress={() => timeoutAction()} />
</div>
);
render(<App />, document.getElementById("root"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment