Bhawna
Bhawna

Reputation: 705

Not able to update reducer state in redux

On change of select I want to save the value in reducer. But How can I pass the value into state. below is the code I am using.

container/header/index.js

const changeCloud = () => {
  return ('hello');
}

const mapStateToProps = () => ({
  cloud: changeCloud(),
  menuItems: menuItems,
})

const mapDispatchToProps = (dispatch) => ({
  setCloud: () => {
    dispatch(setCloud('sf'));
  },
})

const Header = connect(
  mapStateToProps,
  mapDispatchToProps
)(HeaderPresentational);

component/header/index.js

setCloudClick(evt) {
    this.setState({
      value: evt.target.value,
    }, function () {
      this.props.setCloud('this.state.value');
    });
  }

render(){
    return(
    <select onChange={this.setCloudClick} value={this.state.value}>
        <option value="zscaler.net">zscaler.net</option>
        <option value="zscalerOne.net">zscalerOne.net</option>
        <option value="zscaler.net">ZscalerTwo.net</option>
        <option value="Zscaler Private Access">Zscaler Private Access</option>
    </select>
);
}

reducer.js

function reducer(state, action) {
  switch (action.type) {
    case 'SET_CLOUD' :
      alert(action.text);
      return state;
    default :
      return state;
  }
}
export default reducer;

Upvotes: 0

Views: 34

Answers (1)

Shubham Khatri
Shubham Khatri

Reputation: 281950

From the callback, you need to pass the value and not the string

setCloudClick(evt) {
    this.setState({
      value: evt.target.value,
    }, function () {
      this.props.setCloud(this.state.value);  // pass this.state.value here
    });
  }

However, when you are storing value in store, you need not store it locally. You can dispatch the value like

index.js

setCloudClick(evt) {
    this.setState({
      value: evt.target.value,
    }, function () {
      this.props.setCloud(this.state.value);
    });
  }

render(){
    return(
         <select onChange={this.setCloudClick} value={this.state.value}>
            <option value="zscaler.net">zscaler.net</option>
            <option value="zscalerOne.net">zscalerOne.net</option>
            <option value="zscaler.net">ZscalerTwo.net</option>
            <option value="Zscaler Private Access">Zscaler Private Access</option>
        </select>
    );
}

container/header/index.js

const changeCloud = () => {
  return ('hello');
}

const mapStateToProps = () => ({
  cloud: changeCloud(),
  menuItems: menuItems,
})

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

const Header = connect(
  mapStateToProps,
  mapDispatchToProps
)(HeaderPresentational);

Upvotes: 1

Related Questions