Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call function after dispatch from redux has finished

All around it but not quite as I have enough of an idea of redux-thunk and of react-router but I am not getting this seemingly simple idea of:

Call a change in route programmatically via <Route/>'s history.push('/') after an action has finished dispatching to the store, this to happen when a button is pushed.

const LoggerRedux = ({stateProp, LogIn}) => {
    return(
      <div>
        <h2>Here is the button. Use this to login</h2>
        <Route render={({ history}) => (
          <button
            type='button'
            onClick={

            //Something that calls {LogIn}
            //and then the history.push('/')

            }
            >
            Log yo Arse Inn
          </button>
        )}>

        </Route>
      </div>
    )
}

const mapStateToProps = (state) => {
  return {
    stateProp : state
  }
}
const mapDispatchToProps = (dispatch) => {
  return {
    LogIn : () => dispatch({
      type : 'AUTHENTICATE'
    }),
    LogOut : (bool) => dispatch({
      type : 'LOGGED_OUT',
      bool
    })
  }
}
const LoginConn = connect( mapStateToProps, mapDispatchToProps)(LoggerRedux);

Layman explanations and examples of all things I mentioned/tagged would also be nice

like image 460
KellysOnTop23 Avatar asked Nov 30 '17 03:11

KellysOnTop23


People also ask

How do I run a function after dispatch?

call the function history. push('/') within your Login function, this looks to be within your reducer AUTHENTICATE function. dispatch an action that calls history. push after successful authentication look at redux-promise or redux-saga , redux-thunk is a bit trickier to do, but its possible.

What happens after dispatch in Redux?

Something happens in the app, such as a user clicking a button. The app code dispatches an action to the Redux store, like dispatch({type: 'counter/incremented'}) The store runs the reducer function again with the previous state and the current action , and saves the return value as the new state.

Is Redux dispatch asynchronous?

Introduction. By default, Redux's actions are dispatched synchronously, which is a problem for any non-trivial app that needs to communicate with an external API or perform side effects. Redux also allows for middleware that sits between an action being dispatched and the action reaching the reducers.

What is the input for the dispatch function in Redux?

dispatch is a function of the Redux store. You call store. dispatch to dispatch an action. This is the only way to trigger a state change. With React Redux, your components never access the store directly - connect does it for you.


2 Answers

Have your action creator return a promise. This way when you invoke it, you can use .then() and in your then handler you can push a new address to the history.

Thunks will return functions normally, but a promise differs in that you can act after completion.

Example:

static myActionCreator(somevar) {
  return dispatch => {
    return new Promise((resolve, reject) => {
      dispatch({
        type: "myaction",
        something: somevar
      });

      resolve()
    });
  }
}

So in this case, your thunk returns a promise. Then when you invoke like this:

this.props.myActionCreator(somevar)
.then(() => {
  this.props.history.push('/winning')
})

This thunk is just dispatching an action, but you could have some async call in there that has a callback, etc. and you resolve on completion.

like image 165
Hashibuto Avatar answered Sep 17 '22 20:09

Hashibuto


I think what you are looking for is Redux Saga.

You can use the TakeEvery Effect, which will trigger the function you want every time a specific action is called.

Example :

import { takeEvery } from `redux-saga/effects`

function* fetchUser(action) {
  ...
}

function* watchFetchUser() {
  yield takeEvery('USER_REQUESTED', fetchUser)
}

Take a look at the doc and read this article

like image 33
sidali Avatar answered Sep 16 '22 20:09

sidali