简体   繁体   中英

ReactJS REST API call making twice

I have testing this code React Rest service code. When I open the page, I see its making two calls to REST server.

Code to call the server API

export const App = (): React.FC<user[]> => {
  const [user, setUser] = useState<user | undefined>();
  useEffect(() => {
    fetch('https://jsonplaceholder.typicode.com/users')
      .then((response) => response.json())
      .then((json) => setUser(json));
  }, []);

Here is the full acritical:

https://cynoteck.com/blog-post/how-to-call-web-api-with-useeffect-hook-in-react-typescript/#What_is_a_RESTful_API

I also tested this with my local machine REST service, its making two calls.

May I know how to prevent this duplicate request?

attaching browser image在此处输入图像描述

this is a new behavior that was added on react version 18, it only happens on development and exactly when using strict mode, it will not occur on production,

I think they added this behavior (mounting and unmounting components twice on the first render), to catch some bugs (when not cleaning some subscription you put on the useEffect).

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