0

Hi guys I am trying to build a react search box component but it keeps throwing me this error:

Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component.

It also says: the above error occurred in the component:

But I haven't called any or used hooks in the component. Here is the code for my component:

export default function Passengerpage() {
  const { longitude, setlongitude } = useContext(LocationContext);
  const { latitude, setlatitude } = useContext(LocationContext);
  const [searchResults, setResults] = useState([]);

  async function getNearbyPlaces(query, lat, long, limit = 5, radius = 10000) {
    let baseUrl = "https://api.tomtom.com/search/2/poiSearch";
    let queryString = `limit=${limit}&lat=${lat}&lon=${long}&radius=${radius}&key=${process.env.REACT_APP_API_KEY}`;
    let response = await axios.get(`${baseUrl}/${query}.json?${queryString}`);
    return response.data.results;
  }

  async function onSearchChange(query) {
    if (query.length > 0) {
      let results = await getNearbyPlaces(query, latitude, longitude);
      setResults(results);
    }
  }

  return (
    <div>
      <ReactSearchBox
        placeholder="Search for nearby places"
        matchedRecords={searchResults
          .map((result) => ({
            key: result.id,
            name: result.poi.name,
            dist: result.dist,
            value: `${result.poi.name} | ${(result.dist / 1000).toFixed(2)}km `,
          }))
          .sort((a, b) => a.dist - b.dist)}
        data={searchResults
          .map((result) => ({
            key: result.id,
            name: result.poi.name,
            dist: result.dist,
            value: result.poi.name,
          }))
          .sort((a, b) => a.dist - b.dist)}
        onSelect={(place) => console.log(place)}
        autoFocus={true}
        onChange={(query) => onSearchChange(query)}
        fuseConfigs={{
          minMatchCharLength: 0,
          threshold: 1,
          distance: 100000,
          sort: false,
        }}
        keys={["name"]}
      />
      <Addride />
    </div>
  );
}

Any advice would be helpful!

  • I also don't see any out of place hook calls. Do you have a stacktrace? – Halcyon Sep 05 '22 at 15:07
  • @Halcyon No i dont know what that is I am relatively new to react – Tahsan Samin Sep 05 '22 at 15:17
  • A stacktrace is not a React thing, it's a programming this. Usually when you get an error you get a message and a stacktrace: https://en.wikipedia.org/wiki/Stack_trace it should give you an indication where the 'wrong' hook call is. – Halcyon Sep 05 '22 at 15:22

0 Answers0