Skip to content

Instantly share code, notes, and snippets.

@manoelneto
Created August 10, 2018 15:44
Show Gist options
  • Save manoelneto/fad5d0a1b9bcb0543ccbd93583c7713a to your computer and use it in GitHub Desktop.
Save manoelneto/fad5d0a1b9bcb0543ccbd93583c7713a to your computer and use it in GitHub Desktop.
// Loading provider
const LoadingContext = React.createContext({
pushLoading: () => {},
removeLoading: () => {},
})
class LoadingProvider extends Component {
state = {
loadingCount: 0
}
pushLoading = () => {
this.setState({loadingCount: this.state.loadingCount + 1});
}
removeLoading = () => {
this.setState({loadingCount: this.state.loadingCount - 1});
}
render() {
return <LoadingContext.Provider value={{
pushLoading: this.pushLoading,
removeLoading: this.removeLoading,
}}>
{this.props.children}
{this.state.loadingCount > 0 ? (
// Renderizo a div do loading
) : ""}
</LoadingContext.Provider>
}
}
// Loading.js
class Loading extends Component {
componentDidMount() {
this.props.pushLoading()
}
componentWillUnmount() {
this.props.removeLoading()
}
render() {
return null;
}
}
export default props => {
return <LoadingContext.Consumer>
{({pushLoading, removeLoading}) => (
<Loading pushLoading={pushLoading} removeLoading={removeLoading} />
)}
</LoadingContext.Consumer>
}
// app.js
const App = (props) => {
return <LoadingProvider>
// other child
<UserList />
<PostList />
</LoadingProvider>
}
// UserList.js
class UserList extends Component {
state = {
loading: false
}
loadUser = () => {
this.setState({loading: true}, () => {
loadPromise().then(() => {
this.setState({loading: false})
})
})
}
render() {
<div>
// render user list
{loading ? <Loading />}
</div>
}
}
// PostList.js
class PostList extends Component {
state = {
loading: false
}
loadUser = () => {
this.setState({loading: true}, () => {
loadPromise().then(() => {
this.setState({loading: false})
})
})
}
render() {
<div>
// render post list
{loading ? <Loading />}
</div>
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment