I am working on a form using react-hook-form for React Native, which I want to submit to the server but I am getting stuck when I want to clear the TextInput and update the object as null, instead of that the object itself is not present in the json.
Step 1 - I have a TextInput which I want to clear by pressing a button.
Step 2 - I am doing this by passing the reference of the input to the button.
So the object is - before clearing the input
{
input1: "some random text",
object2: "random2",
object3: "random3"
}
After pressing the clear button the text input is getting cleared but the form object is now like -
{
object2: "random2",
object3: "random3"
}
input1 object is missing I want it to be there with its value updated to null.
Source code for TextInput
<View style={[AuthorizationStyle.authorizationTokenInput]}>
<Controller control={control} render={({value}) => (
<TextInput placeholder="Bearer token (optional)"
onChangeText={(itemValue) => setValue("bearerToken", itemValue == "" ? null : itemValue)}
style={[AuthorizationStyle.textInput]}
ref = {ref}
/>
)}
name="bearerToken"
defaultValue={null}
/>
</View>
Source code for clear Button
<View style={[AuthorizationStyle.deleteInput]}>
<TouchableOpacity onPress = {() => ref.current.value = null}>
<FontAwesomeIcon icon={faBackspace} size={22} color="#dc3545" style={[AuthorizationStyle.iconStyle]}/>
</TouchableOpacity>
</View>
Source code for useEffect -
let ref = useRef("");
let val = ref.current.value;
useEffect((val) => {
if(val == "") {
val = null
}
setValue("bearerToken", val)
}, [val])
Code is not optimized yet sorry for this raw code but need to handle this first on urgent basis.
You should use the resetField function provided by useForm for that:
const {resetField} = useForm(/* form options */);
and use it like
onPress={() => resetField('theFieldName')}
This will reset the fields value to its defaultValue. You can override that value if you want:
onPress={() => resetField('theFieldName', {defaultValue: ''})}
Note that the form state should be kept and managed by react-hook-form as the single source of truth. There is most likely no need to have it in a separate state or to use additional refs.