Nastro
Nastro

Reputation: 1769

Why Redux doesn't re-render component?

I have a component with componentDidMount() method which gets info from server like this:

componentDidMount() {
    this.getAccount();
}

getAccount = async () => {
    try {
        this.res = await API.get(`account`, {});
        this.props.setData(this.res.data);
    } catch (err) {
        this.props.history.push(`/add`);
    }
}

And I have a reducer which store the info:

const initialState = {}

const accountReducer = (state = initialState, action) => {
    if (action.type === 'SET_ACCOUNT_DATA') {
        return action.data;
    } else {
        return state;
    }
}

export default accountReducer;

But my component doesn't re-render after action performed. Why? My action code is:

export const setData = (data) => {
    return {
        type: 'SET_ACCOUNT_DATA',
        data
    }
}

Please help, what am I doing wrong?

UPDATE: My map methods are:

const mapStateToProps = (state) => ({

})

const mapDispatchToProps = (dispatch) => {
    return {
        setData: (data) => {
            return dispatch(setData(data));
        }
    }
}

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

Mu action import is correct. Checked.

Upvotes: 3

Views: 2213

Answers (2)

sbqq
sbqq

Reputation: 1091

  1. In your reducer you probably want to copy origin state and add your changes to it so I think that your reducer should probably looks like:

    const accountReducer = (state = initialState, action) => {
      if (action.type === 'SET_ACCOUNT_DATA') {
        return {...state, data: action.data};
      } else {
        return state;
      }
    }
    
  2. If your component has mapStateToProps(), which is returning empty object then the component is not going to re-render if there is no props/state change... Your mapStateToProps() method should maybe look like:

    const mapStateToProps = state => ({
      data: state.yourReducer.yourDataFromStore
    })
    

Upvotes: 4

avani kothari
avani kothari

Reputation: 739

did you check by putting console.log('state:::',state); inside mapStateToProps() ? Is it called again? also can you try this

const accountReducer = (state = initialState, action) => {
    if (action.type === 'SET_ACCOUNT_DATA') {
        return Object.assign({}, state, {...state, data:action.data });
    } else {
        return state;
    }
}

and in your mapStateToProps

const mapStateToProps = (state)=>({
  data: state.reducername.data
})

Upvotes: 3

Related Questions