S
S
Sergey2020-12-01 19:03:18
React
Sergey, 2020-12-01 19:03:18

How to get state from redux store?

How to get the state chosenAddress in the second component, after changing it in the first one? Crashes with an error that getState is not a function. What's wrong?

There is index.js, where I import registrationReducer into rootReducer ------------------------------

import {createStore, compose, applyMiddleware} from 'redux';
import {Provider} from 'react-redux';
import rootReducer from './store/reducers/rootReducer';

const store = createStore(
  rootReducer
)

store.subscribe(() => {
  console.log('Subscribe', store.getState());
})

There is a reducer ------------------------------------
const initialState = {
    chosenAddress: '',
}

export default function registartionReducer(state = initialState, action) {
    switch (action.type) {
        case 'changeAddress':
            return {
                ...state,
                chosenAddress: action.value,
            }
        default:
            return state
    }
}

There is an action ------------------------------------
export function changeAddress(payload) {

    return {
        type: 'changeAddress',
        value: payload
    }
}

There is a component #1 that has a linkClick method (the state changes, it works out) ---------------------------------- --
import { connect } from 'react-redux';
import { changeAddress } from "../store/actions/changeRegistration";

class Component1 extends React.Component {
  constructor(props) {
        super(props);

        this.state = {
            chosenAddress: '',
        }
    }

    linkClick() {
        console.log(this.state.chosenAddress);
        this.props.changeAddressAction(this.state.chosenAddress);
    }

  render() {
        ...
    }
}

const mapStateToProps = (state) => {
    return {
        chosenAddress: state.settingsReducer.chosenAddress,
    }
}

const mapDispatchToProps = (dispatch) => {
    return {
        changeAddressAction: value => dispatch(changeAddress(value)),
    }
}

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

There is a component 2 (there is an error)------------------------------
import registartionReducer from '../store/reducers/registration.js';

class Component2 extends React.Component {

    componentDidMount() {
        console.log(registartionReducer.getState().chosenAddress);
    }
    
  render() {
        ...   
    }
}

export default Component2;

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question