Baryarte
Baryarte

Reputation: 63

Reset fields in a form after submitting data with React Native

I'm trying to add an User to my database using a form, but after I click on the submit button I would like to reset the fields in the form too.

I'm setting the states like this and I'm trying to submit my data at the onPress prop:

export default function Cadastro({}) {
  const [nome, setNome] = useState("");
  const [idade, setIdade] = useState("");
  const [email, setEmail] = useState("");
  const [estado, setEstado] = useState("");
  const [cidade, setCidade] = useState("");
  const [endereco, setEndereco] = useState("");
  const [telefone, setTelefone] = useState("");
  const [nome_usuario, setNome_usuario] = useState("");
  const [senha, setSenha] = useState("");
  const [confirmacao, setConfirmacao] = useState("");

  var newUser = {
    nome: nome,
    idade: idade,
    email: email,
    estado: estado,
    cidade_id: cidade,
    endereco: endereco,
    telefone: telefone,
    nome_usuario: nome_usuario,
    senha: senha,
  };

  return (
    <SafeAreaView style={{ flex: 1 }}>
      <FocusAwareStatusBar barStyle="light-content" backgroundColor="#88c9bf" />
      <ScrollView>
        <KeyboardAvoidingView style={styles.background}>
          <View style={styles.infobox}>
            <Text style={styles.infotext}>
              As informações preenchidas serão divulgadas apenas para a pessoa
              com a qual você realizar o processo de adoção e/ou apadrinhamento,
              após a formalização do processo.
            </Text>
          </View>

          <View style={styles.regform}>
            <Text style={styles.label}>INFORMAÇÕES PESSOAIS</Text>

            <TextInput
              style={[styles.textInput, { marginBottom: 36 }]}
              placeholder="Nome completo"
              autoCorrect={false}
              value={nome}
              onChangeText={setNome}
            />

            <TextInput
              style={[styles.textInput, { marginBottom: 36 }]}
              placeholder="Idade"
              autoCorrect={false}
              value={idade}
              onChangeText={setIdade}
            />

            <TextInput
              style={[styles.textInput, { marginBottom: 36 }]}
              placeholder="E-mail"
              autoCorrect={false}
              value={email}
              onChangeText={setEmail}
            />

            <TextInput
              style={[styles.textInput, { marginBottom: 36 }]}
              placeholder="Estado"
              autoCorrect={false}
              value={estado}
              onChangeText={setEstado}
            />

            <TextInput
              style={[styles.textInput, { marginBottom: 36 }]}
              placeholder="Cidade"
              autoCorrect={false}
              value={cidade}
              onChangeText={setCidade}
            />

            <TextInput
              style={[styles.textInput, { marginBottom: 36 }]}
              placeholder="Endereço"
              autoCorrect={false}
              value={endereco}
              onChangeText={setEndereco}
            />

            <TextInput
              style={styles.textInput}
              placeholder="Telefone"
              autoCorrect={false}
              value={telefone}
              onChangeText={setTelefone}
            />

            <Text style={styles.label}>INFORMAÇÕES DE PERFIL</Text>

            <TextInput
              style={[styles.textInput, { marginBottom: 36 }]}
              placeholder="Nome de usuário"
              autoCorrect={false}
              value={nome_usuario}
              onChangeText={setNome_usuario}
            />

            <TextInput
              style={[styles.textInput, { marginBottom: 36 }]}
              placeholder="Senha"
              autoCorrect={false}
              value={senha}
              onChangeText={setSenha}
            />

            <TextInput
              style={styles.textInput}
              placeholder="Confirmação de senha"
              autoCorrect={false}
              value={confirmacao}
              onChangeText={setConfirmacao}
            />

            <Text style={styles.label}>FOTO DE PERFIL</Text>

            <View style={styles.container}>
              <TouchableHighlight onPress={() => {}}>
                <View style={styles.button}>
                  <Image source={require("../../assets/controlpoint.png")} />
                  <Text style={{ color: "#757575" }}>adicionar fotos</Text>
                </View>
              </TouchableHighlight>
            </View>

            <View style={{ paddingTop: 32, paddingBottom: 24 }}>
              <SubmitButton
                text="FAZER CADASTRO"
                onPress={() => {
                  AddUsuario(newUser);
                }}
              />
            </View>
          </View>
        </KeyboardAvoidingView>
      </ScrollView>
    </SafeAreaView>
  );
}

I also tried to create a function that sets the states like setNome(''), but then I get the "Invalid hook call" error.

Also, is there a better way to initialize multiple states other than the way I did above?

Thank you for your help!

Upvotes: 2

Views: 808

Answers (2)

Nooruddin Lakhani
Nooruddin Lakhani

Reputation: 6967

Change this for all fields

"onChangeText={setNome}" to onChangeText={(text) => setNome(text)}

clear values after submit

const clearForm = () => {
    setName('');
    setIdade('');
    ......
}

<SubmitButton
   text="FAZER CADASTRO"
   onPress={() => {
    AddUsuario(newUser);
    clearForm();
   }}
/>

Upvotes: 1

Dishant Chanchad
Dishant Chanchad

Reputation: 787

Because you're using a functional component you can use Hooks as follows. If you have conditional renders your code check that todoInput is defined in the function passed to useEffect. I assumed your state variable is called todoText in the dependency list.

import {useRef, useEffect} from 'react';


let AddTodo = ({ dispatch }) => {
    const todoInput = useRef();
    useEffect(()=>todoInput.current.clear(),[todoText]);

      return (
          <TextInput 
              ref={todoInput}
              onSubmitEditing = { e => { dispatch(addTodo(e.nativeEvent.text)) } } 
          />
      )
    }

Upvotes: 0

Related Questions