danday74
danday74

Reputation: 57126

How to execute function when action is fired or completes?

THE SHORT QUESTION

What is best practice for executing a function after an action has been triggered?

I'm tempted to detect the action in middleware. If its the action I want, execute the function and then pass the action to the reducers. But this seems a bit hacky?

FYI The function uses jQuery to get all codemirror elements on the page and clears the history of all of them

THE FULL QUESTION WITH BACKGROUND (for those who want more depth)

The code I am working with (not my code) fires an action (FAKE_ACTION)

The payload of FAKE_ACTION is another action (REAL_ACTION).

FAKE_ACTION stores REAL_ACTION in a list in global redux state.

Later on, REAL_ACTION will be pulled from the list and triggered.

After REAL_ACTION is triggered I want to execute a function. Where should this function live?

Upvotes: 1

Views: 579

Answers (4)

danday74
danday74

Reputation: 57126

Some useful answers here but none are quite what I'm after (given the messy codebase I'm working with) / didn't feel right.

I ended up using store.subscribe which allows you to subscribe to changes in the store's data and react accordingly.

See https://redux.js.org/docs/api/Store.html#subscribe for more info

Upvotes: 0

Hemadri Dasari
Hemadri Dasari

Reputation: 34004

You can define a function. In your actions, post an Ajax call when you dispatch a response you will be calling either a success callback or an error callback. So in dispatch, you can define your function.

export function loginUser(email, password) {
  return (dispatch, getState) => {
    dispatch(loginRequest())
    return ajax.post(URL_PREFIX+"/auth/login", { email, password })
      .then(res => {          
              // console.log("path: ", path)
          dispatch(loginSuccess(res))
         const value = loginUtils.getCurrentUser()  //function that you are talking about    
      })
      .catch(errors => {
        dispatch(loginFail(errors));
      })
  }
}

and in loginUtils the function getCurrentUser() is like below

export function getCurrentUser() {
return 'test'
}

Upvotes: 1

Krasimir
Krasimir

Reputation: 13539

It looks like you are wondering how to handle async operations (side effects) in a redux context. This happens indeed via a middleware but you don't have to write your own. There are projects like redux-thunk or better redux-saga. It is basically logic that stands between the dispatch and the reducers.

Upvotes: 1

yogesh agrawal
yogesh agrawal

Reputation: 726

you have to perform asynchronus operation for this. you can use either middleware like redux-thunk or either you can go for javascript promise or any other callback asynchronus function.

Upvotes: 1

Related Questions