Alan Souza
Alan Souza

Reputation: 7795

React Redux: dispatch returning data to component

I have a component with a form that will add an item. When the form is submitted I'm dispatching an async action using redux, something like this:

_onSubmit(event) {
    const { dispatch } = this.props;
    const { data } = this.state;
    event.preventDefault();

    dispatch(addItem(data));
  }

Now, my back-end will create a task with an id that I can track progress. Usually this given task will take a while to complete, so I want to show the notification bar.

For me to track that task, I need to retrieve the task id for this given task that is in progress. So I thought about adding a callback function so that I could get this information from the dispatcher, something like this:

_onSubmit(event) {
        const { dispatch } = this.props;
        const { data } = this.state;
        event.preventDefault();

        dispatch(addItem(data, (id) => console.log(id)));
      }

But this feels kind of "hacky" as there is a two-way data communication going on.

Question: What is the redux way of achieving this?

Upvotes: 0

Views: 2395

Answers (2)

Josep
Josep

Reputation: 13071

There are a few different ways to achieve this. I've done something very similar using redux-saga with eventChannels.

You could also use redux-cycles or redux-observable for the same purpose: creating an observable that's subscribed to the signals of your API, and that it dispatches actions as they come.

I am not a fan of redux-thunk. Maybe there could be a way to accomplish this using redux-thunk, but I'm quite certain that it won't be easy/elegant.

Upvotes: 0

shobhit1
shobhit1

Reputation: 654

There can be multiple ways to achieve the same results for this problem.

I would say use Redux Thunk(Middleware), which will enable you to fire multiple actions from your action creator.

Then you should write something like this:

_onSubmit(event) {
 const { dispatch } = this.props;
 const { data } = this.state;
 event.preventDefault();

 dispatch(addItemActionCreator(data));
}

In your action creator, use a promise(as thunk will allow you to do that as well):

export const addItemActionCreator = (data) => (dispatch) => {
 Promise.get('data').then((data) => {
  dispatch({ type: STORE_DATA_ID, id: data.id })
 })
}

This will dispatch an action that will store id, in your state.

In your component, use connect to subscribe to id and your component will always have the latest id value.

Hope this helps.

Upvotes: 1

Related Questions