Reputation: 606
I am working on a react.js app where i am working with redux state management.I have created 2 radio buttons and I am switching between them and setting the state variable correspondingly.
Here's my active button:
<form >
<input type="radio" id="html" name="status" value="HTML" onClick={this.setClientStatus("Active")}/>
<label for="html">Active</label><br/>
<input type="radio" id="css" name="status" value="CSS" onClick={this.setClientStatus("InActive")}/>
<label for="css">InActive</label><br/>
</form>
Here's my dispatch method:
const mapDispatchToProps = dispatch => ({
setClientName: clientName=>dispatch(onSetClientName(clientName)),
setClientStatus:clientStatus=>dispatch(onSetClientStatus(clientStatus))
});
export default connect(mapStateToProps, mapDispatchToProps)(toReturn);
Here's my method to change the state:
constructor(props) {
super(props);
this.setClientStatus=this.setClientStatus.bind(this);
}
setClientStatus(status)
{
this.props.setClientStatus(status)
}
action.js
export const SET_STATUS='CLIENT/SET_STATUS'
actionCreator.js
export function onSetClientStatus(clientStatus)
{
// console.log(clientStatus)
return {type:Actions.SET_STATUS,clientStatus}
}
clientReducer.js
const initialState = {
clientStatus:"",
};
case Actions.SET_STATUS:{
{
console.log(action.clientStatus)
return Object.assign({},state,{clientStatus:action.clientStatus})}
}
Even when I try to log the status in actionCreator or reducer,without clicking on radio buttons I see toggling in value of status whenever the state of app changes due to other state variables.I am calling the setClientStatus method only on onClick
of radio buttons but I dont know how they are getting logged on every state change in the app.
Here's my full working app.use npm start
to run then go to add a client
then just toggle between the radio buttons.
Github repo here
Thanks
Upvotes: 0
Views: 437
Reputation: 6316
In the onClick
prop of both your inputs you are invoking the setClientStatus
instead of passing a function. It happens on every render, that's why you see it being toggled on other state changes.
Instead of:
onClick={this.setClientStatus("Active")}
onClick={this.setClientStatus("InActive")}
you probably need to have:
onClick={() => this.setClientStatus("Active")}
onClick={() => this.setClientStatus("InActive")}
Upvotes: 1