How to stop axios send multiple requests to an api?

Viewed 955

I am trying to make an autocomplete input field in my application. I am getting the suggestions from an external API. When I start the app, a lot of calls are sent to the api and they are continuing to be sent until I stop the app. I am not even clicking the button, but the function getSuggestions sends requests. Why is this happening?

import axios from "axios";
import { useEffect, useState } from "react";
import { Button, Form, Row, Col } from "react-bootstrap";
import constants from "../../constants";

function Autocomplete() {
    const [suggestions, setSuggestions] = useState([]);

    function getSuggestions(inputText) {
        const config = {
            params: { search_term: inputText, search_type: 'listings' },
            headers: {
                'x-rapidapi-host': 'zoopla.p.rapidapi.com',
                'x-rapidapi-key': 'x'
            }
        };
        axios.get(`${constants.baseUrl}auto-complete`, config)
             .then(response => {
                 const suggestionsList = response.data.suggestions.map(x => x.value);
                 setSuggestions(suggestionsList);
                 console.log(suggestions);
            })
    }

    useEffect(()=>{
        getSuggestions('Oxford');
    },[]);

    return (
        <Row className="d-flex align-items-center">
            <Col>
                <Form.Control type="text" placeholder="Area" />
            </Col>
            <Col>
                <Button variant="primary" type="button" onClick={getSuggestions('Oxford')}>
                    Search
                </Button>
            </Col>
        </Row>
    );
}
export default Autocomplete;
1 Answers

on your onClick you need to change (inside of the return)

getSuggestions('Oxford')

to

() => getSuggestions('Oxford')

Otherwise it will run right away on the first render along with your useEffect

Related