Home > Enterprise >  Redux state has changed, why doesn't it trigger a re-render? (Redux-saga)
Redux state has changed, why doesn't it trigger a re-render? (Redux-saga)

Time:12-09

I'm using react redux redux saga

I'm facing the issue that when I'm rendering the page (GET call) The calls should be like:

  1. constructor
  2. render()
  3. componentDidMount
  4. render()

But I'm just reaching up to componentDidMount, mapDispatchToProps is dispatching the action, API call is working by which getting the response from the server and the data is updated into the state. BUT somewhere it gets lost and my component is not even re rendering. Up to the reducer, I'm getting the data where I'm returning action.items.

itemReducer.js

const itemReducer = (state = initialState, action) => {
  switch (action.type) {
    case types.GET_ALL_ITEMS_SUCCESS:
      console.log("itemReducer-----", action.items); //getting the data over here
      return action.items;
    default:
      return state;
  }
};

itemPage.js (component)

class ItemsPage extends React.Component {
      componentDidMount() {
        this.props.loadItems();
      }

     render() {
        const { items } = this.props; // not even it renders, so not getting data
        ...
        return (<div>...</div>);
     }
}

const mapStateToProps = (state) => {
  return {
    items: state.items,
  };
};

const mapDispatchToProps = (dispatch) => {
  return {
    loadItems: () => dispatch(loadAllItemsAction()),
  };
};

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

Please give some suggestions, Thanks in advance :D

CodePudding user response:

There isn't issue in the code that you posted. To make sure I pretty much copy pasted the code you shared, filled in the missing parts and it works just fine: https://codesandbox.io/s/3tuxv?file=/src/index.js

My guess what might be wrong is that your items are not stored in state.items but under some different path or you might be missing the react-redux Provider, but it is impossible to say for sure without seeing more of your code.

CodePudding user response:

You need to understand that the calls of render/componentDidMount are not so linear as it could be expected. componentDidMount fires when all children were mount. And it doesn't means that render() was finished already.

Read here for more info: https://github.com/facebook/react/issues/2659

  • Related