Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using updated redux state right after dispatch [duplicate]

I'm using react-redux, and added a 'filters' field to my redux state, which contains all filters I want to use for receiving data from my db.

My goal is to receive data from db with the updated filters right after a filter is added. This is what I got so far:

--- actions.js ---

...
    export function addFilter(filter, value) {
        return {
            type: 'ADD_FILTER',
            filter: filter,
            value: value
        }
    }
...

--- reducer.js ---

...
      case 'ADD_FILTER':
            return update(state, {
                filters: {
                    $merge: {
                        [action.filter]: action.value
                    }
                }
            });
...

--- filteringComponent.js ---

...
    addFilterAndUpdateData(filter, value) {
        this.props.addFilter(filter, value);
        this.props.getData(this.props.filters); 
        // this.props.filters is connected to state.filters.
        // it DOES update, but not right away. so when getData is dispatched
        // this.props.filters holds the old object and not the updated one
    }
...

After adding the filter, I want to dispatch right away the getData action, in order to receive the data with the latest filters from the db.

The problem is that this.props.filters is not updated yet. Is there a way to 'wait' for the update?

The best solution I came up with so far is to use componentWillReceiveProps, but then I have to add conditions (since I don't necessarily want to dispatch getData every time my props are changed, only when it's as a result of filters update)

What would be the right 'react-redux' approach here?

like image 482
Bar Kedem Avatar asked Nov 08 '22 04:11

Bar Kedem


1 Answers

Asking for the right react-redux approach for this case, using componentWillReceiveProps is right, while asking for the best practice I recommend you read about the following:

  1. redux-saga: it will handle your async actions and make one listen for another (which is your use-case here)

  2. ImmutableJs, it will handle for you changing your component props just if any of its value changes (which is this.props.filters in your case, so it just get to you the updated data if it's really updated)

  3. React.PureComponent, this is can be used instead of React.Component, it will improve your performance handling rendering React component by checking deeply in props object if any changes.

Again, if you don't have the time or the flexibility in your project to apply this, writing some checks in componentWillReceiveProps is not wrong.

like image 114
Basim Hennawi Avatar answered Nov 14 '22 23:11

Basim Hennawi