searchfilter with using react hook(useEffect / useState)

352 views Asked by At

I am trying to create a searchBar. When I type some value on input, I would like my listitems from github api to be re-listed with the value on searchBar.

import './App.css';

function App() {

  const [datas, setDatas] = useState([]);
  const [userid, setUserid] = useState('');
  
  const inputChanged = (event) => {
    setUserid(event.target.value)
  }

  const searchBar = () => {

  }

  useEffect(() => {

    fetch('https://api.github.com/search/repositories?q=react')
    .then(response => response.json())
    .then(data => {
      setDatas(data.items)
    })
  },[])
  return (
    <div className="App">
      <h1>Repositories</h1>
        <input id="searchInput"type="text" placeholder="search" name="search" value={userid} onChange={inputChanged}/>
        <button onClick={searchBar}>Search</button>
      <table>
        <tbody>
          <tr>
           <th>Name</th>
           <th>URL</th>
          </tr>
          {
          datas.map((data, index) => 
           <tr key={index}>
             <td>{data.full_name}</td>
             <td><a href={data.html_url}>{data.html_url}</a></td>
           </tr>
          )
        
          }
        </tbody>
      </table>
    </div>
  );
}

export default App; 

Here is my code and the image of the localhost

enter image description here

1

There are 1 answers

0
nico263nico On BEST ANSWER

useEffect has an array at the end, when left empty what's in useEffect only update once. You can add variables to that array, to update when that variable changes.

Here you need to write: useEffect(your function,[userid]);