Skip to content

Instantly share code, notes, and snippets.

View thiagovilla's full-sized avatar
🐕
Certified dog person

Thiago Villa thiagovilla

🐕
Certified dog person
View GitHub Profile
// products/ducks/productsOperations.js
import {
getProducts,
patchProduct as _patchProduct
// other API endpoints (HTTP verbs)
} from 'api/products' // webpack 'api' alias
import {
fetchProductsRequest,
fetchProductsSuccess,
@thiagovilla
thiagovilla / normalize.js
Created August 31, 2018 19:13
Function that normalizes a collection (an array) of objects into an 'allIds' ordered array and a 'byId' object whose keys are each individual object id
const normalize = items => ({
byId: items.reduce((_items, item) => ({
..._items,
[item.id]: item
}), {}),
allIds: items.map(item => item.id)
})
export default normalize
@thiagovilla
thiagovilla / api.js
Created August 22, 2018 18:56
Axios-wrapped global API service with JWT authentication and base URL environment variable
// api.js
import axios from 'axios'
const API_URL = process.env.API_URL
const AUTH_TOKEN = ... // from local storage, session etc.
const api = axios.create({
baseURL: API_URL,
headers: { 'Authorization': 'JWT ' + AUTH_TOKEN }
})
@thiagovilla
thiagovilla / ordersFetch.js
Last active August 22, 2018 13:49
Fetch thunk with Redux dispatch() and triplet async actions (request, success, error)
// duck/ordersFetch.js
import { getOrders } from '../api/orders'
import {
fetchOrdersRequest, // 'request' or 'begin'
fetchOrdersSuccess,
fetchOrdersError // 'error' or 'failure'
} from './ordersActions'
const fetchOrders = params =>
dispatch => {
@thiagovilla
thiagovilla / order.js
Last active August 22, 2018 20:07
Function-based GET endpoint with RESTful params object
// api/orders.js
import api from './api'
// 'sanitize' function here
const getOrders = ({ offset = 0, limit = 25, query = '', ...otherParams }) =>
api.get(`/orders?offset=${offset}&limit=${limit}&query=${query}`)
.then(response => ({
items: response.data.results.map(sanitize),
count: response.data.count
@thiagovilla
thiagovilla / ordersActions.js
Last active August 22, 2018 20:08
Triplet action creators for async API fetch in Redux
// duck/ordersActions.js
export const FETCH_ORDERS_REQUEST = 'FETCH_ORDERS_REQUEST'
export const FETCH_ORDERS_SUCCESS = 'FETCH_ORDERS_SUCCESS'
export const FETCH_ORDERS_ERROR = 'FETCH_ORDERS_ERROR'
export const fetchOrdersRequest = _ => ({ // _ = ()
type: FETCH_ORDERS_REQUEST
// no payload
})