Nelson Kehinde
Nelson Kehinde

Reputation: 223

Is there a way to set a state with textinput when onChangeText is already in use?

Im trying to set a state with the values from a textinput (which is a reusable component), Im using onChangeText to setFieldValue (useFormikContext()), I also want to set a state which will be sending to the Parent component. I tried using onChange but noticed it saves the text without the last word/number, for instance if I type 0123456789, the setFieldValue gets 0123456789, but the other one (with onChange) gets only 012345678 (without 9).

Here is the code:

function AppFormField({ name, width, childToParent, ...otherProps }) {
  const { setFieldTouched, setFieldValue, errors, touched, values } =
    useFormikContext();

    
  
     
  return (
    <>
      <TextInput
        onBlur={() => setFieldTouched(name)}
        onChangeText={(text) => setFieldValue(name, text)}
        onChange={() => childToParent(bn)}
        value={values[name]}
        width={width}
        {...otherProps}
      />
      <ErrorMessage error={errors[name]} visible={touched[name]} />
    </>
  );
}

Parent Component:

...

const [bn, setBN] = useState("");

  const childToParent = (childdata) => {
    setBN(childdata);
    console.log(childdata);
  };
  console.log("bn");
  console.log(bn);


...

 return (

...

<UppFormField
              keyboardType="numeric"
              autoCorrect={false}
              // icon="bank"
              name="acct_number"
              placeholder="Account Number"
              style={{ paddingRight: 50 }}
              childToParent={childToParent}
            />

...
)

Upvotes: 0

Views: 412

Answers (1)

Adam Katz
Adam Katz

Reputation: 6962

Make a middle function called

const onTextChange = (text) => {
  setFieldValue(text)
  parentFunction(text)
}

then TextInput takes has

onChangeText={onTextChange}

Upvotes: 1

Related Questions