Closed otech47 closed 5 years ago
Here's a possible implementation
const DECREMENT_PENDING_NETWORK_CALLS = 'environment/DECREMENT_PENDING_NETWORK_CALLS';
const INCREMENT_PENDING_NETWORK_CALLS = 'environment/INCREMENT_PENDING_NETWORK_CALLS';
const RESET_PENDING_NETWORK_CALLS = 'environment/RESET_PENDING_NETWORK_CALLS';
// Reducer
const initialState = {
pendingNetworkCalls: 0
};
// Actions
import api from '../scripts/api';
export function decrementPendingNetworkCalls() {
return {
type: DECREMENT_PENDING_NETWORK_CALLS
};
}
export function incrementPendingNetworkCalls() {
return {
type: INCREMENT_PENDING_NETWORK_CALLS
};
}
export function resetPendingNetworkCalls() {
return {
type: RESET_PENDING_NETWORK_CALLS
};
}
export default function reducer(state = initialState, action) {
switch (action.type) {
case DECREMENT_PENDING_NETWORK_CALLS:
return {
...state,
pendingNetworkCalls: state.pendingNetworkCalls - 1
};
case INCREMENT_PENDING_NETWORK_CALLS:
return {
...state,
pendingNetworkCalls: state.pendingNetworkCalls + 1
};
case RESET_PENDING_NETWORK_CALLS:
return {
...state,
pendingNetworkCalls: 0
};
default:
return state;
}
}
import React from 'react';
import { connect } from 'react-redux';
import { BarLoader } from 'react-css-loaders'
import Flex from './Flex'
import theme from '../styles/theme'
const Loader = ({ color, size, show }) => {
return show && (
<Flex
position='fixed'
top={0}
left={0}
width='100vw'
height='100vh'
bg='overlay'
zIndex={1000}
center
>
<BarLoader color={color} size={size}/>
</Flex>
)
}
Loader.defaultProps = {
color: theme.colors.white,
size: 8
}
const mapStateToProps = ({ environment }) => {
return {
show: environment.pendingNetworkCalls > 0,
};
};
export default connect(mapStateToProps)(Loader);
import {
decrementPendingNetworkCalls,
incrementPendingNetworkCalls,
resetPendingNetworkCalls
} from './environment'
export function fetchData() {
return (dispatch) => {
dispatch(incrementPendingNetworkCalls())
return (
api.graph(...)
.then(res => {
dispatch(decrementPendingNetworkCalls())
})
.catch(err => {
console.error(err)
dispatch(resetPendingNetworkCalls())
})
)
}
}
See https://github.com/setlife-network/setblocks/pull/15#discussion_r244896044