skip to Main Content

i am new in React, i have a begginer question I can’t solved it.

I have a simple Input and Button to get data from API.

// function to handleChange

const [searchQuery, setSearchQuery] = useState('')
const [getCityData, setGetCityData] = useState('');
const [cityData, setCityData] = useState([]);

const handleChange = (e) => {
    setSearchQuery(e.target.value)
}


// function to handle button get City from API

const handleClick = () => {
    if (searchQuery !== "") {
        try {
            setGetCityData(searchQuery);
            fetchCity();
        } catch (error) {
            console.log(error);
        }
    }
}


// function to get data from API

const fetchCity = async () => {
    try {
        const res = await axios.get(url)
        console.log(res.data);
        setCityData(res.data);
        console.log(cityData);
    } catch (error) {
        console.log(error);
    }
}

The problem is, when I press the button after fill the input, it always log with empty array first.
First line is data from API, the second line is log from function
console log

and when fill the input with another City, it display the previous data.
I think when we fetch the city it did not update the latest value.

How we fix this? or how we ‘delay’ the request API after useState is fill with the latest value.

Thank you for your attention.

2

Answers


  1. The issue you’re facing is due to the asynchronous nature of the fetchCity function. When you call it, it starts executing in the background, but the code below it continues to run immediately, without waiting for the API call to finish.

    To fix this, you can use the useEffect hook in React to watch for changes in the searchQuery state variable. Whenever searchQuery changes, you can then call the fetchCity function to get the updated data.

    Here’s an updated version of your code that should resolve the issue:

    const [searchQuery, setSearchQuery] = useState('');
    const [getCityData, setGetCityData] = useState('');
    const [cityData, setCityData] = useState([]);
    
    const handleChange = (e) => {
        setSearchQuery(e.target.value);
    }
    
    // function to handle button get City from API
    const handleClick = () => {
        if (searchQuery !== "") {
            try {
                setGetCityData(searchQuery);
            } catch (error) {
                console.log(error);
            }
        }
    }
    
    // function to get data from API
    const fetchCity = async () => {
        try {
            const res = await axios.get(url);
            console.log(res.data);
            setCityData(res.data);
            console.log(cityData);
        } catch (error) {
            console.log(error);
        }
    }
    
    useEffect(() => {
        if (getCityData !== "") {
            fetchCity();
        }
    }, [getCityData]);
    
    // rest of your code...
    
    

    In this updated code, we use the useEffect hook to listen for changes to the getCityData state variable. Whenever getCityData changes (i.e., when the button is clicked and the state is set), the fetchCity function is called to fetch the data from the API.

    This ensures that the API call is made only after the getCityData state has been updated with the latest value.

    Login or Signup to reply.
  2. const [searchQuery, setSearchQuery] = useState('')
    const [cityData, setCityData] = useState([]);
    
    const handleChange = (e) => {
    setSearchQuery(e.target.value)
    }
    
    
    // function to handle button get City from API
    
    const handleClick = () => {
        if (searchQuery !== "") {
                fetchCity(searchQuery);
        }
    }
    
    
    // function to get data from API
    
    const fetchCity = async (query) => {
        try {
            // baseUrl is nothing but the url without query eg: https://something.com/?query=
            const url = baseUrl+query
            console.log(url);
            const res = await axios.get(url)
            console.log(res.data);
            setCityData(res.data);
        } catch (error) {
            console.log(error);
        }
    }
    

    i don’t know how you are generating the url on axios get method and passing the search query in the request, it seems like you are passing along with url.
    Try this method by passing query as a param to the fetchCity function and add it with the baseurl

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search