Skip to content

getState for all action creators #180

Closed
@itrelease

Description

@itrelease

So suppose we create dispatcher with promise middleware:

import { createDispatcher, composeStores, createRedux } from 'redux';
import { Provider } from 'redux/react';
import * as stores from './stores/index';
import { thunkMiddleware, promiseMiddleware } from './middlewares';

const dispatcher = createDispatcher(
  composeStores(stores),
  getState => [promiseMiddleware, thunkMiddleware(getState)]
);
const redux = createRedux(dispatcher);

and we have some action:

function fetchTodoItem(todoItemId) {
  return {
    types: [FETCH_TODO_ITEM, FETCH_TODO_ITEM_OK, FETCH_TODO_ITEM_FAIL],
    promise: apiFetchTodoItem(todoItemId),
    todoItemId
  }
}

but in this action I want to check local state on presence this todo item to eliminate request, like this:

function fetchTodoItem(todoItemId, getState) {
  const { todos } = getState();

  if (todos[todoItemId]) {
    return;
  }

  return {
    types: [FETCH_TODO_ITEM, FETCH_TODO_ITEM_OK, FETCH_TODO_ITEM_FAIL],
    promise: apiFetchTodoItem(todoItemId),
    todoItemId
  }
}

The problem that I have no access to getState function.

One of the solutions is to pass to bindActionCreators optional argument getState function:

export default function bindActionCreators(actionCreators, dispatch, getState) {
 return mapValues(actionCreators, actionCreator =>
   (...args) => dispatch(actionCreator(...args, getState))
 );
}

so all actions can get state if they need it.

@gaearon @acdlite

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions