Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

101
Visualizações
Reseting a State React

I have this component that has an input and when you enter a value, it searchs on another component:

export default function Form({ onSearch, countries, setCountries, input, setInput }) {


  function inputHandler(e) {
    setInput(e.target.value);
    onSearch(e.target.value);

    
  }

  

  return (
    <form>
      <input
        type="text"
        value={input}
        placeholder="Search for a country..."
        onChange={inputHandler}
      ></input>)
   

While typing, it sets an input state (setInput) and make a search in this component with a fetch and set another state (setSearch):

function App() {
  const [input, setInput] = useState("");
  const [countries, setCountries] = useState([]);
  const [search, setSearch] = useState([]); 
function onSearch(name) {
    fetch(`https://restcountries.eu/rest/v2/name/${name}`)
      .then((r) => r.json())
      .then((data) => {
        setSearch(data);
      });
  }

While im typing, I see that the state changes and makes the search. The thing is when i´m deleting, the search state changes but when I have nocharacters on the input field, the search state keep info in it. How can I come back to the initial state?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You can add a useEffect in the Form component that watches the length of the input value. If length is 0, it clears the search array.

An example:

useEffect(() => {
   if(input.length === 0) setSearch([]);
}, [input])
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda