React-Redux Connect receives empty state

I have a react component being rendered client side using react router. I have a redux store that is being successfully populated after a dispatch (thus I believe the action and reducer are working correctly)

The problem comes when the connect mapStateToProps function fires, the state is empty.

I have subscribed to the store and console.log(store.getState()) and I can see the state getting set correctly.

Where am I going wrong?

class MyComponent extends Component {

componentWillMount(){

    this.props.fetchData();

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

const mapStateToProps = (state) => {
console.log(state); //This is empty e.g. { form : {} }
return {
    formJSON: state.form
}
};

const mapDispatchToProps = { fetchData};

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

The react router stuff

class ClientApp extends Component {


render() {
    return (
      <Provider store={store}>
        <Router history={history}>
          <Switch>
            <Route exact path="/" >
              <div>Root</div>
            </Route>
            <Route path='/mycomponent'>
              <Container fluid>
                <Row>
                  <Col lg={2}>
                    <MyComponent/>
                  </Col>
                  <Col lg={7}>
                    <OtherComponent />
                  </Col>
                  <Col>
                    <YetAnotherComponent/>
                  </Col>
                </Row>
              </Container>
            </Route>
          </Switch>
        </Router>
      </Provider>      
    );
  }
}

export default ClientApp;

Upvotes: 0

Views: 206

Answers (1)

Aftab22
Aftab22

Reputation: 550

Can you try this:

import React from "react";
import "./cart-icon.styles.scss";
import { connect } from "react-redux";
import { fetchData } from "path for fetchData";

class MyComponent extends Component {
constructor(props){
super(props);
this.state={
formJSON:{}
 }
}

componentDidMount(){
    this.props.fetchData();
}

componentDidUpdate(prevProps){
   if(prevProps.formJSON !==this.props.formJSON){
     this.setState({formJSON})
  }
}

render(){
  console.log(this.state.formJSON);
  return(<div>{this.state.formJSON}</div>
}}

const mapStateToProps = ({form}) => ({
  formJSON:form
});

const mapDispatchToProps = (dispatch) => ({
  fetchData: () => dispatch(fetchData()),
});

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

Upvotes: -1

Related Questions