Search code examples
javascriptreactjsfunctionfetchuse-effect

How to use useEffect on button Click?


I've to call useEffect / Fetch the data only when user click on Search Button otherwise not fetch the data..

Code:

const App = () => {

const[datas,setDatas] = useState([]) 

const [space,setSpace] = useState(null)
const [print, setPrint] = useState(false)


function getData(val){
 // console.log(val.target.value)
  setSpace(val.target.value);
  setPrint(false)
}

// console.log(space)  

  useEffect(() => {
    const fecthPosts = async () => {
      let initial_url = `http://localhost:4000/search` 
      let url = initial_url + "?text=" + space  
       
       const res = await fetch(url);
       const {result} = await res.json();

     setDatas(result);
    fecthPosts();     //I've to call this fetchPosts() when Btn is CLicked
  },[space]);

return(
 <div className="App">
     {                  //Displaying on search
        print?
         <>
        <h2>{space}</h2>  
        <div> 
       {datas.map((field) => 
       <p>{field.title}</p> 
       <p>{field.author}</p> 
       )}
        </div>
        </>
        :null
      }
   <input type="text" onChange={getData} />
   <button onClick={() => { setSpace(true); fetchPosts() }}>search</button>
 </div>
  )
 }
};

export default App;

It's not working Error:

 fetchPosts() is not defined...

I've also tried like this:

function trigger(){
  useEffect(() => {
    const fecthPosts = async () => {
      let initial_url = `http://localhost:4000/search` 
      let url = initial_url + "?text=" + space  
       
       const res = await fetch(url);
       const {result} = await res.json();

     setDatas(result);
    fecthPosts();     //I've to call this fetchPosts() when Btn is CLicked
  },[space]);
}

<button onClick={() => { setSpace(true); trigger() }}>search</button>

It's not working Error:

 React Hook useEffect has unnecessary dependencies:'space'

/PLZZ help to out...


Solution

  • You have to set your fetchPosts outside of the useEffect. Then, you can use a new state search to track any click on the button.

    const App = () => {
      const [datas, setDatas] = useState([]);
      const [space, setSpace] = useState(null);
      const [print, setPrint] = useState(false);
      const [search, setSearch] = useState(false);
    
      const fetchPosts = async () => {
        let initial_url = `http://localhost:4000/search`;
        let url = initial_url + "?text=" + space;
    
        const res = await fetch(url);
        const { result } = await res.json();
        setDatas(result);
      };
    
      function getData(val) {
        setSpace(val.target.value);
        setPrint(false);
      }
    
      useEffect(() => {
        fetchPosts(); // fecthPosts is called each time space changed
      }, [search]);
    
      return (
        <div className="App">
          {
            //Displaying on search
            print ? (
              <>
                <h2>{space}</h2>
                <div>
                  {datas.map((field) => (
                    <>
                      <p>{field.title}</p>
                      <p>{field.author}</p>
                    </>
                  ))}
                </div>
              </>
            ) : null
          }
          <input type="text" onChange={getData} />
          <button onClick={() => setSearch(!search)}>search</button>
        </div>
      );
    };
    
    export default App;