Hanley Soilsmith
Hanley Soilsmith

Reputation: 629

How to access store from componentDidMount()?

This is a possible duplicate of

How to access redux-store from within react's componentDIdMount()

I am finding that example to be confusing and more complicated than my implementation, so I'm going to risk asking again with a simpler code.

I need to access my redux store from componentDidMount(). The following code renders the <h3> component but console.log()'s a null value:

class FinishedPaying extends Component {

  componentDidMount() {
    console.log(this.props.paymentID);
  }
  render() {
    return (
      <div>
        <h3>{this.props.paymentID}</h3>
      </div>
    );
  }
}

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

const mapActionsToProps = (dispatch, props) => {
  return bindActionCreators(
    {
      updatePaymentID: updatePaymentID
    },
    dispatch
  );
};

export default connect(
  mapStateToProps,
  mapActionsToProps
)(FinishedPaying);

reducer code:

import { UPDATE_PAYMENTID } from "../actions/paymentID-actions";

export default function paymentIDReducer(state = "", { type, payload }) {
  switch (type) {
    case UPDATE_PAYMENTID:
      return payload.paymentID;
    default:
      return state;
  }
}

actions code:

export const UPDATE_PAYMENTID = "paymentID:updatePaymentID";

export function updatePaymentID(newPaymentID) {
  return {
    type: UPDATE_PAYMENTID,
    payload: {
      paymentID: newPaymentID
    }
  };
}

Upvotes: 0

Views: 1393

Answers (1)

Ryan Cogswell
Ryan Cogswell

Reputation: 81136

When componentDidMount shows one value (via console.log) and a different value is being rendered, one likely explanation is that the component is being re-rendered immediately after mount (e.g. an initial rendering with a null value and then a redux action is dispatched immediately after the initial rendering that sets the value). You can easily see whether or not this is the case by doing a console.log from the render method. I would expect that you will see two logs from the render method -- one in sync with componentDidMount and then another with the value you see rendered.

In order to have the appropriate value in componentDidMount you will need to change the order of events such that the component isn't rendered until after the state has been updated or re-organize the logic in componentDidMount to leverage other/additional lifecycle methods to recognize when the value changes and deal with it appropriately.

Upvotes: 2

Related Questions