Q
Q
qfrontend2020-08-01 15:20:07
React
qfrontend, 2020-08-01 15:20:07

If there are no asynchronous requests in the action, is it necessary to use middleware?

Greetings) Is it necessary to use middleware if there are no asynchronous requests in the action... but you need to do some calculations, for example, or something else...? Or is middleware only needed for asynchronous actions ?
1) Write like this?

const action = (a, b, c) => {
  return dispatch => {
    const result = (a,b,c) => a + b + c;

    dispatch(dispatchResult(result))
  }
};

const dispatchResult = (result) => {
  return {
    type: ACTION_TYPE,
    payload: {
      result: result
    }
  };
}

2) Or so?
const action = (a, b, c, d) => {
  const result = (a,b,c) => a + b + c;

  return {
    type: ACTION_TYPE,
    payload: {
      result: result
    }
  };
};

How right?
Thank you)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
T
Timur Kostenko, 2020-08-01
@ktim8168

For asynchronous actions, use the redux-thunk middleware, with it you can write this kind of code:

const fetchData = () => {
  return async (dispatch) => {
    // start fetching
    dispatch({type: FETCH_DATA_START});
    try {
      const {data} = await api.fetch('/data');
      dispatch({type: FETCH_DATA_SUCCESS, data});
    } catch (err) {
      dispatch({type: FETCH_DATA_ERROR, error: err});
    }
  }
}

I
Islam Ibakaev, 2020-08-01
@devellopah

count directly in the component

import { sum } from 'lodash'
...
// где-то в методе какого-то компонента
this.props.action(sum([a, b, c]))
...
const action = payload => ({
    type: ACTION_TYPE,
    payload
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question