Search code examples
javascriptreactjstypescriptfetchnavigator

The browser makes 4 requests when sending data to the server


I am having problems with my react component. The problem is that when I want to get the current geographic coordinates, I get them 4 times. The same problem persists if I submit them to the server. The browser makes 4 identical requests instead of one. What could be wrong? This is the complete code for my component:

import React from "react";

export const Component = (): JSX.Element => {
  const getCoords = async (): Promise<GeolocationPosition> => {
    return new Promise((resolve, reject) => {
      navigator.geolocation.getCurrentPosition(
        (position: GeolocationPosition) => resolve(position),
        (error) => reject(error)
      );
    });
  };

  const getData = async () => {
    const { latitude, longitude } = (await getCoords()).coords;
    console.log(latitude + " " + longitude);
    const response = await fetch(`URL`);
    const result = await response.json();
    console.log(result);
  };

  getData();

  return (
    <div>
      <h1>Hello</h1>
    </div>
  );
};



Solution

  • You should not call API in the body ò function component. You should call getData in the useEffect:

      useEffect(() => {
        const getCoords = async (): Promise<GeolocationPosition> => {
          return new Promise((resolve, reject) => {
            navigator.geolocation.getCurrentPosition(
              (position: GeolocationPosition) => resolve(position),
              (error) => reject(error)
            );
          });
        };
    
        const getData = async () => {
          const { latitude, longitude } = (await getCoords()).coords;
          console.log(latitude + " " + longitude);
          const response = await fetch(`URL`);
          const result = await response.json();
          console.log(result);
        };
    
        getData();
      }, []);