Home > database >  How to use Form in Fetching API?
How to use Form in Fetching API?

Time:07-20

I'm trying to use a form on ReactJS and Axios to fetch the API and then search and filter the results based on the form entries. When I hit the Search button nothing happens, my guess is that handleSubmit is not working properly since the code is looking for the empty String after loading the page.

This is my code:

import axios from "axios"; 
import { useEffect, useState, useRef } from "react";

 
  const Routes = () => {

    const DepApt = useRef(null);
    const ArrApt = useRef(null);
  
    const handleSubmit = event => {
      console.log('handleSubmit ran');
      event.preventDefault();
  
      console.log('Dep Apt is:', DepApt.current.value);
      console.log('Dep Apt is:', ArrApt.current.value);
  
    }
    const url = 'https://api.npoint.io/3e926aca0a1e0836b459'
  
    const [data, setData] = useState([])
  
    useEffect(() => {
      axios.get(url).then(json => setData(json.data))
    }, [])
  console.log(data)

    const rte = () => {
      return data.map(user => {
        if ((user.Dep === DepApt.current.value) && (user.Arr === ArrApt.current.value))
        return (
          <ol>
            <li>{user.Max}</li>
          </ol>
        )
      })
      
    }
return (
      
      <>
        <div>
          <div>
            <div/>
          </div>
        </div>
  
        <div>
          <div>
            <div>
              <div>
                <h3>Routes</h3>
                <p>Here you can search for routes from/to XG Airports!</p>
              </div>
            </div>
            <div>
              <form onSubmit={handleSubmit}>
                <div>
                  <div>
                    <div>
                      <div>
                        <label>
                          Departure ICAO
                        </label>
                        <input
                        ref={DepApt}
                      
                          
                        />
                      </div>
  
                      <div className="col-span-6 sm:col-span-3">
                        <label >
                        Arrival ICAO
                        </label>
                        <input
                         ref={ArrApt}
                      "
                         
                        />
                      </div>
                      {rte()}
                    </div>
                  </div>
                  <div>
                    <button
                      type="submit"
             
                   >
                      Search
                    </button>
                  </div>
                </div>
              </form>

            </div>
          </div>
        </div>
<br/>

      </>
    )
  }


  export default Routes;

CodePudding user response:

Your challenge here seems to be that refs don't trigger re-render after ref changes. As to why it renders many times, it may be of many reasons. I've modified your code to showcase that it works if you change the refs away and replace them with useState.

code:

import axios from "axios"; 
import { useEffect, useState } from "react";

 
  const Routes = () => {
  
    const handleSubmit = event => {
      console.log('handleSubmit ran');
      event.preventDefault();
      setShowSearchResult(true);
  
      console.log('Dep Apt is:', apt.DepApt);
      console.log('Dep Apt is:', apt.ArrApt);
      
    }
    const url = 'https://api.npoint.io/3e926aca0a1e0836b459'
  
    const [data, setData] = useState([]);
    const [apt, setApt] = useState({DepApt: '', ArrApt: ''});
    const [showSearchResult, setShowSearchResult] = useState(false);
  
    useEffect(() => {
      axios.get(url).then(json => setData(json.data))
    }, [])
  console.log(data)

    const rte = () => {
      return data.map(user => {
        if ((user.Dep === apt.DepApt) && (user.Arr === apt.ArrApt))
        return (
          <ol>
            <li>{user.Max}</li>
          </ol>
        )
      })
      
    }
return (
      
      <>
        <div>
          <div>
            <div/>
          </div>
        </div>
  
        <div>
          <div>
            <div>
              <div>
                <h3>Routes</h3>
                <p>Here you can search for routes from/to XG Airports!</p>
              </div>
            </div>
            <div>
              <form onSubmit={handleSubmit}>
                <div>
                  <div>
                    <div>
                      <div>
                        <label>
                          Departure ICAO
                        </label>
                        <input
                        onChange={(e) => setApt({...apt, DepApt: e.currentTarget.value}, setShowSearchResult(false) )}
                      
                          
                        />
                      </div>
  
                      <div className="col-span-6 sm:col-span-3">
                        <label >
                        Arrival ICAO
                        </label>
                        <input
                         onChange={(e) => setApt({...apt, ArrApt: e.currentTarget.value}, setShowSearchResult(false))}
                        />
                      </div>
                    </div>
                    {showSearchResult ? rte() : null}
                  </div>
                  <div>
                    <button
                      type="submit"
             
                   >
                      Search
                    </button>
                  </div>
                </div>
              </form>

            </div>
          </div>
        </div>
<br/>

      </>
    )
  }


  export default Routes;

Hope it helps you in achieving what you wanted to achieve :)

  • Related