Last active
October 27, 2018 18:06
-
-
Save ernestofreyreg/7692d98a05745571d55ca179ef927c87 to your computer and use it in GitHub Desktop.
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 axios from 'axios' | |
const createUrlLoader = url => { | |
const initialState = { | |
loading: false, | |
data: null, | |
error: null | |
} | |
const STARTED_LOADING = 'STARTED_LOADING' | |
const ENDED_LOADING = 'ENDED_LOADING' | |
const ERROR_LOADING = 'ERROR_LOADING' | |
const reducer = (state, action) => { | |
switch (action.type) { | |
case STARTED_LOADING: | |
return { ...state, loading: true } | |
case ENDED_LOADING: | |
return { ...state, data: action.data, loading: false } | |
case ERROR_LOADING: | |
return { ...state, error: action.error, loading: false } | |
} | |
return state | |
} | |
const createActions = ({ getState, dispatch }) => { | |
const loadData = () => { | |
if (getState().data || getState().error || getState().loading) { | |
return; | |
} | |
return dispatch(STARTED_LOADING) | |
.then(() => axios.get(url)) | |
.then(response => response.data) | |
.then(data => dispatch(ENDED_LOADING, { data })) | |
.catch(error => dispatch(ERROR_LOADING, { error })) | |
} | |
return { loadData } | |
} | |
return { | |
initialState, | |
reducer, | |
createActions | |
} | |
} | |
export default createUrlLoader |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment