Insert data with TextInput value in React Native, not able to send default values to API

I have a screen that has TextInput‘s. I am trying to insert these TextInput‘s values into the database through the API. And when submitted without typing in the TextInput, I would use the value data that is showing in the TextInput, but with my my below code I keep getting field is required status: 422.

const pressHandle = ({ name, userid }) => {
  axios
    .post(userPostLink, {
      name,
      userid,
    })
    .then((response) => {
      console.log(response.data);
    })
    .catch((error) => {
      console.log(error.response);
    });
};
<TextInput onChangeText={(text) => setUsername(text)} placeholder="username" value="steve" />
<TextInput onChangeText={(text) => setEventid(text)} placeholder="userid" value="fle91739" />

<TouchableOpacity onPress={() => pressHandle({ name, userid })}>
  <Text style={{ color: "blue" }}>Submit</Text>
</TouchableOpacity>

>Solution :

First you would wanna change a little bit your JSX, make use of defaultValue for setting those defaults values.

<TextInput
   onChangeText={text => setUsername(text)}
   placeholder="username"
   value={name}
   defaultValue="steve"
 />
<TextInput
    onChangeText={text => setEventid(text)}
    placeholder="userid"
    value={userid}
    defaultValue="fle91739"
/>

And change your pressHandle, to this:

const pressHandle = ({ name, userid }) => {
  axios
    .post(userPostLink, {
      name: name || "steve",
      userid: userid || "fle91739",
    })
    .then((response) => {
      console.log(response.data);
    })
    .catch((error) => {
      console.log(error.response);
    });
};

Leave a Reply