Riferimento rapido

Cheat Sheet Ecosistema e Middleware di Awesome Redux

Una guida per l'ecosistema Redux: standard Flux Standard Action (FSA), middleware asincroni (redux-thunk, redux-promise) e composizione dei reducer.

· Pubblicato

Una guida di riferimento curata per le librerie fondamentali, action creator e pattern di middleware asincroni in Redux.

Action Creator e Utility

redux-actions

Crea action creator conformi alle specifiche Flux Standard Action (FSA):

import { createAction } from 'redux-actions';

const increment = createAction('INCREMENT', amount => amount);
// increment(42) → { type: 'INCREMENT', payload: 42 }

// Automatically handles error objects:
const err = new Error('Network failure');
// increment(err) → { type: 'INCREMENT', payload: err, error: true }

See: redux-actions on npm


Flux Standard Action (FSA)

Uno standard chiaro per oggetti azione con type, payload, error e meta opzionale:

// Success action
{
  type: 'ADD_TODO',
  payload: { text: 'Write documentation' }
}

// Error action
{
  type: 'ADD_TODO',
  payload: new Error('Failed to save'),
  error: true
}

See: flux-standard-action on GitHub


redux-multi

Consente di inviare un array di azioni in una singola chiamata dispatch:

store.dispatch([
  { type: 'INCREMENT', payload: 1 },
  { type: 'NOTIFY', payload: 'Count updated' }
]);

reduce-reducers

Combina reducer sequenziali senza annidamento di namespace:

import reduceReducers from 'reduce-reducers';

const combined = reduceReducers(
  (state, action) => (action.type === 'ADD' ? state + action.payload : state),
  (state, action) => (action.type === 'MULTIPLY' ? state * action.payload : state)
);

Middleware Asincroni ed Effetti Collaterali

redux-thunk

Permette la scrittura di action creator che restituiscono funzioni con accesso a dispatch e getState:

const fetchUser = (id) => async (dispatch, getState) => {
  dispatch({ type: 'FETCH_USER_REQUEST' });
  try {
    const res = await fetch(`/api/users/${id}`);
    const data = await res.json();
    dispatch({ type: 'FETCH_USER_SUCCESS', payload: data });
  } catch (error) {
    dispatch({ type: 'FETCH_USER_FAILURE', payload: error, error: true });
  }
};

// Dispatch like a normal action:
store.dispatch(fetchUser(42));

See: redux-thunk on GitHub


redux-promise

Middleware per promise conforme a FSA che risolve automaticamente le promise nel payload:

import { createAction } from 'redux-actions';

const fetchPosts = createAction('FETCH_POSTS', async () => {
  const response = await fetch('/api/posts');
  return response.json();
});

// Resolves payload promise automatically:
store.dispatch(fetchPosts());

redux-logger

Registra le transizioni di stato e le azioni inviate direttamente nella console degli strumenti per sviluppatori:

import { createLogger } from 'redux-logger';

const logger = createLogger({
  collapsed: true,
  diff: true
});

Riferimenti

Argomenti correlati