Skip to content

Instantly share code, notes, and snippets.

@evanwinter
Last active November 29, 2018 16:03
Show Gist options
  • Save evanwinter/d7df109c8ae4baa2398009a7f251a477 to your computer and use it in GitHub Desktop.
Save evanwinter/d7df109c8ae4baa2398009a7f251a477 to your computer and use it in GitHub Desktop.
Sample code for handling API calls via Redux.
// via https://medium.com/react-weekly/implementing-graphql-in-your-redux-app-dad7acf39e1b
import {
LOAD_EMPLOYEE_DATA_INITIATION,
LOAD_EMPLOYEE_DATA_SUCCESS,
LOAD_EMPLOYEE_DATA_FAILURE,
} from './constants';
export const employeeUrl = 'http://0.0.0.0:1338/api/employees';
// loadEmployeeDataInitiation :: None -> {Action}
export const loadEmployeeDataInitiation = () => ({
type: LOAD_EMPLOYEE_DATA_INITIATION,
});
// loadEmployeeDataSuccess :: Array -> {Action}
export const loadEmployeeDataSuccess = (data) => ({
type: LOAD_EMPLOYEE_DATA_SUCCESS,
data,
});
// loadEmployeeDataFailure :: Error -> {Action}
export const loadEmployeeDataFailure = (error) => ({
type: LOAD_EMPLOYEE_DATA_FAILURE,
error,
});
export const loadEmployeeData = () =>
(dispatch) => {
dispatch(
loadEmployeeDataInitiation()
);
return fetch(employeeUrl)
.then(res => res.json())
.then(data => {
dispatch(
loadEmployeeDataSuccess(data)
);
})
.catch(error => {
dispatch(
loadEmployeeDataFailure(error)
);
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment