0

When I made this post request with postman it works fine but in this case my django server shows two requests are made and data is also logged twice. I am using jwt tokens if it is related somehow ...

  const controller = new AbortController();
    const [isLoading , setIsLoading] = useState(true)
    const [userData , setUserData] = useState({
        name:"",
        username:"",
        email:""
    })

    const getData = () =>{
      axiosInstance.post("/api/detail/" , {
        signal:controller.signal
      })
      .then((data) =>{
        setUserData({
            name : data.data.name,
            username : data.data.username,
            email : data.data.email
          }
          )
          console.log(data) // this data is logged twice 
          setIsLoading(false)
      return controller.abort()

      }).catch((err)=>{
          console.log("error is" , err)
      })
      return controller.abort()
    }
    useEffect(()=>{
        getData()
    } ,[])

Aryan Kaushik
  • 17
  • 1
  • 5
  • Does this answer your question? [Why useEffect running twice and how to handle it well in React?](https://stackoverflow.com/questions/72238175/why-useeffect-running-twice-and-how-to-handle-it-well-in-react) – Youssouf Oumar Mar 04 '23 at 15:56

2 Answers2

2

You are probably using the StrictMode. Check your main file (index.js, main.js) and see if the component is wrapped like this:

root.render(
  <StrictMode>
    <App />
  </StrictMode>
);

For more details about that, you can see this answer: My React Component is rendering twice because of Strict Mode

Nico
  • 423
  • 1
  • 8
1

useEffect is called twice in the development mode and will only run once on production if strict mode is enabled.

You shouldn't try to use those technics with useRef and if statements in useEffect to make it fire once, or remove StrictMode because react intentionally remounts your components in development to help you find bugs and because of that use effect is called twice. Read here for more information: https://stackoverflow.com/a/72238236/12083049

I would highly recommend using a data-fetching library like react-query or swr to work with API.

swr example:

import useSWR from 'swr'
 
function Profile() {
  const { data, error, isLoading } = useSWR('/api/user', fetcher)
 
  if (error) return <div>failed to load</div>
  if (isLoading) return <div>loading...</div>
  return <div>hello {data.name}!</div>
}