Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
    });
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading