Search code examples
reactjsreduxstatestore

State is empty when using mapStateToProps


The state is empty when I try to map the state from the store to the properties of a component. I try to get a value of a string displayed in JSX but it is missing. I cant manage to get anything to display from the redux store.

Reducer:

const initialState = {
    visibles: "false",
    error: null,
    text: ""
  };

  const rootReducer = (
    state = initialState,
    action
  )  => {
    switch (action.type) {
      case "OPEN_MODAL":
        return {
          ...state,
          visibles: "true",
          error: null
        };

      default:
        return state;
    }
  }

  export default rootReducer;

and index.js

import {createStore } from "redux";
import {Provider } from "react-redux";
import rootReducer from "./components/Redux/Reducer";

const store = createStore(rootReducer);

ReactDOM.render(<Provider store={store}><App /></Provider>, document.getElementById('root'));

consumer of the redux store


import React, { Component } from 'react'
import {connect} from "react-redux";
import styles from "./modal.module.css";


export class Modal extends Component {
    render() {
        console.log(this.props)

        return (

            <div className={styles.root}>
                <p className={styles.title}>{this.props.visible}</p>
            </div>
        )
    }
}

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

export default connect(mapStateToProps)(Modal)

Solution

  • Found the reason why. I had to refactor the Modal class to not use "export class" and then I could get the state from the store with connect.

    class Modal extends React.Component {
    render() {
        console.log(this.props)
    
        return (
    
            <div className={styles.root}>
                <p className={styles.title}>{this.props.visible}</p>
            </div>
        )
    }}