skip to Main Content

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?

2

Answers


  1. Chosen as BEST ANSWER

    SOLUTION: In the root directory of my Next project (where package.json is located), there is also a file called next.config.js. To enable strict mode for Next, you have to change the object nextConfig to contain reactStrictMode: true. Here is my next.config.js that works:

    /** @type {import('next').NextConfig} */
    const nextConfig = {
      reactStrictMode: true,
    }
    
    module.exports = nextConfig
    

  2. -> 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

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