Reseting a State React

Viewed 26

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?

1 Answers

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])
Related