skip to Main Content

I have data in mongo.
I am getting my data, but when see my console.log(). it show me data multiple times.
Can you please tell me why is it happening and how to fix it?

const [teams, setTeams] = useState([])

console.log(teams)

const fetchData = async () => {

  try {
       const { data } = await axios('/api/getTeam/data')
       setTeams(data)

    } catch (error) {
       console.log(error)
    }
  }
 

useEffect(() => {
 fetchData()
}, [])

if I refresh page, I am getting multiple fetch.
This is my output in console.log()
Can you please tell me why is it happening and how to fix it?
Thank you

[]
[]
[]
[]
(14) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
(14) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
(14) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
(14) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]

2

Answers


  1. That you have multiple logs does not mean you have multiple fetch. This is how react works. It re-renders. Components are just functions and React calls them again and again when you update some state. If you use Strict Mode, react calls everything twice.

    Login or Signup to reply.
  2. If you are running React in StrictMode:

    https://react.dev/reference/react/StrictMode

    each fetch / axios equivalent of fetch that you do in a useEffect will be done twice.

    Either turn off StrictMode or deal with it – for example the library react-easier (a long with many others) will debounce this and only fetch once:

    https://www.npmjs.com/package/react-easier

    Disclaimer: I am the author of react-easier.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search