Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react props not updating with redux store

I've always used react-redux connect to configure props but I need to use a react Component to use lifecycle methods. I'm noticing that my props that I'm grabbing from the store seem to be static and they do not update as the store updates.

Code:

class AlertModal extends Component {

  title
  isOpen
  message

  componentDidMount() {
    const { store } = this.context
    const state = store.getState()
    console.log('state', state)
    console.log('store', store)
    this.unsubscribe = store.subscribe(() => this.forceUpdate())
    this.title = state.get('alertModal').get('alertModalTitle')
    this.isOpen = state.get('alertModal').get('isAlertModalOpen')
    this.message = state.get('alertModal').get('alertModalMessage')
    this.forceUpdate()
  }

  componentWillUnmount() {
    this.unsubscribe()
  }

  updateAlertModalMessage(message) {
    this.context.store.dispatch(updateAlertModalMessage(message))
  }
  updateAlertModalTitle(title) {
    this.context.store.dispatch(updateAlertModalTitle(title))
  }

  updateAlertModalIsOpen(isOpen) {
    this.context.store.dispatch(updateAlertModalIsOpen(isOpen))
  }

  render() {

    console.log('AlertModal rendered')
    console.log('AlertModal open', this.isOpen) <======= stays true when in store it is false

    return (
      <View

How do I set up title, isOpen, and message so they reflect the store values at all times?

like image 833
BeniaminoBaggins Avatar asked May 20 '17 04:05

BeniaminoBaggins


1 Answers

It should be something like this. In your Confirmation component:

const mapStateToProps = (state) => {
  return { modalActive: state.confirmation.modalActive };
}

export default connect(mapStateToProps)(Confirmation);

In your reducer index file, is should be something like this:

const rootReducer = combineReducers({
  confirmation: ConfirmationReducer
});

I believe you have your own reducer file called ConfirmationReducer here. It should be something like this.

import { ON_CONFIRM } from '../actions';

const INITIAL_STATE = {modalActive: true};
export default function(state = INITIAL_STATE, action) {
  console.log(action);
  switch (action.type) {
    case ON_CONFIRM:
      return { ...state, modalActive: action.payload };
  }

  return state;
}

Make sure you write your own action creator to create an action with the above type and relevant payload of boolean type.

Finally you should be able to access the property from the store inside your Confirmation component like this:

{this.props.modalActive}

You have not posted entire code, so it makes very difficult to give a solution to the exact scenario. Hope this helps. Happy coding!

like image 68
Ravindra Ranwala Avatar answered Oct 07 '22 13:10

Ravindra Ranwala