Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redux- mapStateToProps not working

I have a react component that makes an AJAX call in componentWillMount and backs the data received in response to a redux store. Here is code

componentWillMount() {
  var self = this;
  var xmlhttp = new XMLHttpRequest();
  xmlhttp.onreadystatechange = function() {
    if (this.readyState === 4 && this.status === 200) {
      console.log(this.responseText);
      var json = JSON.parse(this.responseText);
      var data = {
        json
      };
      self.props.dispatch({
        type: "ADD_Exams",
        data
      });
    }
  };
  xmlhttp.open("GET", "http://127.0.0.1:8000/getExams/", true);
  xmlhttp.send();
}

In the reducer, I am assigning the data received in action to an array defined in the reducer state.

const initialState = {
  exams:[]    
}

const examreducer = (state = initialState, action) => {
  switch (action.type) {
    case "ADD_Exams":
      return {
        ...state,
        exams: [...state.exams, action.data.json]
      };
    default:
      return state;
  }
};

But when I use mapStateToProps to read exams variable I get undefined.

const mapStateToProps = (state) => {
    return {
        exams: state.exams
    }
}

export default connect(mapStateToProps)(Exam); 

I am creating store like this

import { Provider } from "react-redux";
const store = createStore(loginReducer, examReducer);
ReactDOM.render(
  <Provider store={store}>
    <Exam />
  </Provider>,
  document.getElementById("root")
);

registerServiceWorker();

console.log(this.props.exams) prints undefined. What is the problem here?

like image 343
saim2025 Avatar asked Nov 27 '22 06:11

saim2025


1 Answers

I ran into the same problem. My mistake was because I was doing wrong export/import of the component.

export:

export class MyComponent extends React.Component
...
export default connect(mapStateToProps, mapDispatchToProps)(MyComponent);

import:

import { MyComponent } from './MyComponent';

to solve I removed the export on the class and used the default:

import MyComponent from './MyComponent';
like image 184
Lorcalder Avatar answered Dec 05 '22 05:12

Lorcalder