How can I pass a setter function (useState) as prop using navigation.navigate? I have it set up as the following:
const [firstName, setfirstName] = useState('');
const [dob, setDOB] = useState('');
const [medicalConditions, setMedicalConditions] = useState('');
const [allergies, setAllergies] = useState('');
const [bloodtype, setBloodtype] = useState('');
const [height, setHeight] = useState('');
const [weight, setWeight] = useState('');
return (
<KeyboardAvoidingView style={styles.container} behavior="padding">
<View style={styles.buttonContainer}>
<TouchableOpacity
onPress={() => navigation.navigate('Profile', {
setMedicalConditions: (a) => setMedicalConditions(a),
setAllergies: (b) => setAllergies(b),
setBloodtype: (c) => setBloodtype(c),
setHeight: (d) => setHeight(d),
setWeight: (e) => setWeight(e)
})}
style={[styles.button, styles.buttonOutline]}>
<Text style={styles.buttonText}>Edit</Text>
</TouchableOpacity>
</View>
</View>
</KeyboardAvoidingView>
)
It works fine but I get an error saying :
Non-serializable values were found in the navigation state. Check:
Profile > params.setMedicalConditions (Function)
This can break usage such as persisting and restoring state. This might
happen if you passed non-serializable values such as function, class
instances etc. in params. If you need to use components with callbacks in
your options, you can use 'navigation.setOptions' instead. See
https://reactnavigation.org/docs/troubleshooting#i-get-the-warning-non-
serializable-values-were-found-in-the-navigation-state for more details.
I tried using DeviceEventEmitter but it says it’s deprecated.
2
Answers
You cannot pass a setter function with
navigate
to another component!What you have to do is to create a function that updates your state and pass it to the child component instead of all these setter functions.
The function will recieve two parameters, the first is to indicate which state to update, and the second is for its new value :
Now this function you can pass it to the child component
And use it to update state in the parent one
This will update the
height
state in the parent component.You have to create function X in screen A(contain setter) and pass to screen B. when you call function X in screen B, setter is called.
and
if you only want to save value, use useRef() insted