I am building an app with React Native. Currently, I am having an issue passing a value to an action prop.
I have a form update action call in the onChangeText method of a TextInput component. When the text is changed, I mutate the text and pass it to the update action, like so:
onChangeText={value => {
let frequency = value + ' ' + this.state.frequencyTerm;
console.log(frequency) // this is not undefined but expected value
this.props.reminderFormUpdate({prop: 'frequency', frequency});
}
However, when I check the value passed to the reminderFormUpdate function (simple console.log statement), it says the value is undefined. I also logged the value of frequency just before passing it to the action, and it is the correct value. So why is this happening?
I've found if I don't mutate the value received from the TextInput, and change the line to:
this.props.reminderFormUpdate({prop: 'frequency', value});
the value received by the action is no longer undefined, but obviously it is not the value I want to set my frequency prop to. The action also works perfectly for other props when the value is not mutated before being passed to the function, but why can't I mutate the value?
Here is my reminderFormUpdate function (the function works as expected with other props so I don't think this is the issue):
export const reminderFormUpdate = ({prop, value}) => {
return {
type: 'REMINDER_FORM_UPDATE',
payload: {prop, value},
};
};
Thanks in advance for your help :-)
reminderFormUpdate = ({prop, value})
In this code block, "value" represents the property of the passed object. So prop and value are not just regular function parameters. They are property names. This called "object destructuring". more info
so, what's the deal in here? When you mutate the value, you passed that in your function as "frequency". And when you destructuring the passed object in your reminderFormUpdate, you still looking for property "value". But now it's "frequency".
So you should do it like this:
this.props.reminderFormUpdate({prop: 'frequency',value: frequency});
Or change it in your reminderFormUpdate function:
export const reminderFormUpdate = ({prop, frequency}) => {
return {
type: 'REMINDER_FORM_UPDATE',
payload: {prop, frequency},
};
};