简体   繁体   中英

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>
  );
};


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();
  }, []);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM