Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

94
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!