Skip to content

Instantly share code, notes, and snippets.

@corsonknowles
Last active October 5, 2018 18:02
Show Gist options
  • Save corsonknowles/0d201bdf11aca49cd1db6fd338caa269 to your computer and use it in GitHub Desktop.
Save corsonknowles/0d201bdf11aca49cd1db6fd338caa269 to your computer and use it in GitHub Desktop.
/* eslint-disable no-undef, camelcase */
import ReactOnRails from ‘react-on-rails’;
import { receiveErrors, clearErrors } from ‘./errorActionCreators’;
// protect your Reducers from silently failing by using constants
export const GET_ITEM = 'GET_ITEM';
export const DELETE_ITEM = 'DELETE_ITEM';
export const RECEIVE_ITEMS = 'RECEIVE_ITEMS';
// synchronous actions
export const getAdminUser = text => ({
type: GET_ITEM,
text,
});
export const deleteAdminUser = text => ({
type: DELETE_ITEM,
text,
});
export const receiveAdmins = payload => ({
type: RECEIVE_ITEMS,
payload,
});
// promise handling helper functions
export const status = response => {
if (response.status >= 200 && response.status < 300) {
return Promise.resolve(response);
} else {
return Promise.reject(response);
}
};
export const unwrap = response => response.json();
// DRY out your code by defining headers once
export const headers = {
‘X-Requested-With’: ‘XMLHttpRequest’,
‘X-CSRF-Token’: ReactOnRails.authenticityToken(),
‘Content-Type’: ‘application/json’,
Accept: ‘application/json’,
};
// asynchronous actions with error handling
export const updateItem = (item) => {
const url = `/api/items/${item.id}`;
const body = JSON.stringify({ item });
return (dispatch) => {
fetch(url, {
credentials: ‘same-origin’,
method: ‘PATCH’,
body,
headers,
})
.then(status)
.then(unwrap)
.then(responseJSON => dispatch(receiveItem(responseJSON)))
.catch(unwrap)
.then(responseJSON => dispatch(receiveErrors(responseJSON)));
};
};
export const showItems = () => {
const url = '/api/items/';
return (dispatch) => {
fetch(url, {
credentials: 'same-origin',
method: 'GET',
headers
})
.then(status)
.then(unwrap)
.then(responseJSON => dispatch(receiveItems(responseJSON)))
.catch(unwrap)
.then(errors => dispatch(receiveErrors(errors)));
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment