poldeeek
poldeeek

Reputation: 333

component not re rendering on props change redux react

My component with filters doesn't re-render after changes in Redux state. With console.log() I can see that action and reducer works. ObjectFilter.js after changes gives good result with console, but doesn't re-render.

mapReducer.js

const mapReducer = (state = initState, action) => {
    switch(action.type) {
        case actions.SET_FILTERS:
            console.log('SET_FILTERS', state)
            return({
                ...state,
                filters: action.filters
            })
        default:
            return state;
    }
}

export default mapReducer;

mapActions.js

export const setFilters = (el, old_filters) => {
    let filters = old_filters;
    let new_el = !old_filters[el];

    filters[el] = new_el;
    console.log(filters)
    return (dispatch, getState) => {
        dispatch({
            type:actions.SET_FILTERS,
            filters: filters
        })
    }
}

objectFilters.js

class ObjectFilters extends Component {


    changeFilterHandler = (el) => {
        this.props.setFilters(el, this.props.filters);
    }

    render () {
        console.log(this.props.filters)
        return (
        /* some code */
    );}
}

const mapDispatchToProps = dispatch => {
    return {
        setFilters: (el, filters) => dispatch(setFilters(el, filters))
    }
}

const mapStateToProps = state => {
    return {
        filters: state.mapRedux.filters
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(ObjectFilters);

Upvotes: 0

Views: 96

Answers (1)

Jagrati
Jagrati

Reputation: 12222

The problem in your code is that you are mutating the old_filters directly, instead make a clone of it and then update filter value. Never mutate state and prop directly

export const setFilters = (el, old_filters) => {
    let filters = {...old_filters}; // using spread operator to create a clone
    let new_el = !old_filters[el];
    filters[el] = new_el;

    return (dispatch, getState) => {
        dispatch({
            type:actions.SET_FILTERS,
            filters: filters
        })
    }
}

Upvotes: 2

Related Questions