简体   繁体   中英

Redux-thunk actions

I have actions/index.js file with action creators, and I am using redux-thunk as middleware. This is the code:

export const fetchUser = () => async dispatch => {
    const res = await axios.get('/api/current_user');
    dispatch({type: FETCH_USER, payload: res.data});
};

export const handleToken = (token) => async dispatch => {
    const res = await axios.post('/api/stripe/', token);

    dispatch({type: FETCH_USER, payload: res.data});
};

export const submitSurvey = (values, history) => async dispatch => {
    const res = await axios.post('/api/Surveys', values);

    history.push('/Surveys');
    dispatch({type: FETCH_USER, payload: res.data});
};

export const scrollMovement = (scrollValue) => dispatch => {
    dispatch({type: SCROLL_MOVE, payload: scrollValue})
};

export const selectConfig = (id) => dispatch => {
  dispatch({type: "SELECT_CONFIG", payload: id})
};

And I have a question. Should I write action creators, which do not send a request to external API (for example, scrollMovement and selectConfig), at the same style, as I write hadleToken, submitSurvey, and fetchUser action creators?

I hope that you understand my question. If not, add comments, I will explain.

For an a synchronous flow of data, you just need to return an object as normal you do, because, under the hood, thunk middleware intercepts actions of the type function before the dispatch is generated.

So for scrollMovement and selectConfig you don't have to return a function because these follow an a synchronous flow of data

export const scrollMovement = scrollValue => {
    return {type: SCROLL_MOVE, payload: scrollValue}
};

export const selectConfig = id => {
  return {type: "SELECT_CONFIG", payload: id}
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM