Search code examples
reactjsreduxreact-reduxredux-form

Unable to access this.props data inside constructor, react+redux


I'm using redux, redux-form and react-select inside the Form component as shown below. I am having problem with using props as a multi-select value of the form.

Multi-select value displays and works correctly when props are loaded, or when the page is refreshed. However it doesn't seem to work correctly during normal use cases.

Smart container calls asyncconnect to dispatch book-runner data, and I'm using connect in this component to access this.props.bookRunners.

class Form extends Component {
  constructor(props) {
    super(props);
    const bookRunnerArray = this.getBookRunnerArray(this.props.bookRunners.bookRunners);
    this.state = {
      options: bookRunnerArray,
      value: [],
    };
  }

Connecting to store:

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

const mapDispatchToProps = (dispatch) => {
  return { actions: bindActionCreators(dealActions, dispatch) }
};
export default connect(mapStateToProps, mapDispatchToProps)(Form);

I think this.props.bookRunners is empty when I try to set initial state inside the constructor. I tried using componenetWillMount() but no luck. Please help!


Solution

  • Adding the code below solved the problem. super(props) and prop accessed in constructor were all still "fetching". Therefore did not have the data needed. componenetWillMount also was the same case. However, I was able to access the data from componentWillReceiveProps(). Please let me know if anyone has any thoughts.

      componentWillReceiveProps() {
        if(!this.props.bookRunners.isFetching && this.state.options.isEmpty){
          const bookRunnerArray = this.getBookRunnerArray(this.props.bookRunners.bookRunners);
          this.setState ({
            options: bookRunnerArray,
          })
        }
      }
    

    --- day 2 was working on another container with the same problem. And decided that componentDidUpdate() + initializing inside constructor behaved more consistently.

    So below + constructor shown above.

      componentDidUpdate() {
        if(!this.props.bookRunners.isFetching && this.state.options.isEmpty){
          const bookRunnerArray = this.getBookRunnerArray(this.props.bookRunners.bookRunners);
          this.setState ({
            options: bookRunnerArray,
          })
        }
      }