Redux actions based on / linked to other actions

I am building a Redux application (my first one) and it is a little unclear how many connections fit between activities.

My application has several forms whose values ​​are serialized in a url.

For example, there is an input field for a specific search, and when the key is activated, the url parameter is updated. There are several other input fields after this template.

In my top level index.js

, I have several blocks of code that look like this:

// Within the declaration of a high-level component
onForm1Change={(key, value) => {
        // Listened to by "formValues" state cross-section reducer
        store.dispatch({
            type: actions.FORM1_CHANGE,
            key: key,
            value: value
        });

        // Listened to by "url" state cross-section reducer, leads to a url param update.
        // Has it own logic that is based upon the formValues state.
        // Must run after FORM1_CHANGE finishes
        store.dispatch({
            type: actions.UPDATE_URL,
            formValues: store.getState().formValues
        });
    }
}

      

Something about doing things like UPDATE_URL

doesn't seem right. This action does not stand alone ... it relies on other actions to be sent first.

Is this connection between actions a code smell? Are there any general methods for de-pairing / reorganizing these actions?

+3


source to share


2 answers


I think it is completely OK to chain synchronous actions. You can also use middleware like redux-thunk to make it easier to read (since you will be storing your action dispatcher functions as a creator action). Below is an article on this topic.



+3


source


This is how I did it,

The pruning store middleware is defined that will detect if any dispatched action has a property queryString

and updates the URL with it.

import createHistory from "history/createBrowserHistory";

function queryStringMiddleware(history) {
  return store => next => action => {
    const { payload } = action;
    if (payload.queryString) {
      history.push({
        search: queryString
      });
    }
    next(action);
  };
}

const history = createHistory();
const middlewares = [queryStringMiddleware(history)];
const store = configureStore({}, middlewares);

      



Then in your action:

const onForm1Change = (key, value) => {
  store.dispatch({
    type: actions.FORM1_CHANGE,
    key: key,
    value: value,
    queryString: "?the=query"
  });
};

      

+1


source







All Articles