Home > Mobile >  Why does my NextJS Code run multiple times, and how can this be avoided?
Why does my NextJS Code run multiple times, and how can this be avoided?

Time:06-16

I've been trying to connect my frontend and backend for a webapp and I have an issue where, when a user creates an account, multiple objects for that user get created in the database. I used console.log and found that my NextJS code is repeating. I found this slightly related post: Component functions runs multiple times react However, it deals with problems with async calls that I already solved with null/undefined checks. This is my current user register code:

const handleUser = async (user) => {
  var bUserExists = false

  await axios.get(GET_USER(user.email))
    .then(response => {
      bUserExists = true;
    })
    .catch(err => {
      bUserExists = false
    })

  if(!bUserExists) {
    bUserExists = true;
    await axios.post(CREATE_USER(), {
      email: user.email,
      name: user.name,
    }).then(newUser => {
      console.log(newUser.data)
      if(newUser.data) {
        router.push('/form/p1')
      }
    }).catch(err => {
      console.log(err)
    })
  }
}

const { user, error, isLoading } = useUser();
  
if(isLoading) return <div>Loading...</div>;
if(error) return <div>{error.message}</div>;
if(user) {
  // try to get the user from the database
  // if the user doesn't exist, create one
  handleUser(user)
}

When I create a user with this code, my backend outputs this:

(Sorry, I don't have enough rep to post images yet ;-; ) https://i.gyazo.com/fd83cf9362b0e88977dfb277687ca071.png

Weird, right? It repeats so quickly that the user isn't even created by the time the second call comes in.

I've come to the conclusion that NextJS is repeating the code on both the client and server, but my knowledge of Next/React is too little for that to be very accurate. Why is it that my code (that should only run once) is running multiple times?

CodePudding user response:

-> In react due to Strict mode enable it render every page Two times(only in development environment). -> so we can remove Strict mode enable by just removing this Strict mode wrapper from index.js in react.

<React.StrictMode>
    <div>
      <ComponentOne />
      <ComponentTwo />
     </div>
 </React.StrictMode>

-> and next.js is based on react so you have to find the way like how to disable strict mode in next.js here is official doc link[disable strict mode next.js][1] [1]: https://nextjs.org/docs/api-reference/next.config.js/react-strict-mode

  • Related