0

idk why but my useEffect happens twice and its messing up my code :(

useEffect(() => {
axios
  .post("/register", {
    fullname,
    username,
    email,
    password,
  })
  .then((response) => {
    setMessage(JSON.stringify(response.data.success));
    console.log(message);
    if (message === "true") {
      setOpen(true);
      setTimeout(() => {
        navigate("/signin");
      }, 3000);
    } else {
      setErrorMessage(
        JSON.stringify(Object.keys(response.data.msg.keyPattern)[0])
      ); //TODO: create better validation message
    }
  })
  .catch((error) => {
    return error;
  });
}, [email, fullname, message, navigate, password, username]);

im kinda new to API calls. what im trying to achive is getting a response from the server with the success msg, if its true there is snackbar that i want to open and then navigate to signin. if the success msg is false i want to alert an error.

another problem that i think is happening because of the useEffect is that even thought i have email property and user property that are unique, it saves in the database more than once.

enter image description here

app.js file -

import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
import reportWebVitals from "./reportWebVitals";

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

reportWebVitals();

  • 1
    Duplication of data in the db must be restricted in the backend.. you have to check the user exist or not before onboarding newUser into your database... Regarding useEffect, you have so many Dependencies, so its hard to tell which state variable causes the api repetition.. – sms Aug 17 '22 at 14:52
  • Read about React.StrictMode to understand why its called twice – Dennis Vash Aug 17 '22 at 14:52
  • sms all this dependencies are required by vscode.. i cant remove anything without getting an error. – Yarden Yosef Aug 17 '22 at 15:01
  • ah sorry I updated my answer. You need to remove the StrictMode tags. – ratzownal Aug 17 '22 at 15:33

3 Answers3

0

It could be because of the strict mode. Try this and check if it is working. Remove <React.StrictMode>

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import { MainPage } from './pages/MainPage';


const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  /* <React.StrictMode> */
    <MainPage />
  /* </React.StrictMode> */
);
ratzownal
  • 284
  • 1
  • 8
0

I think the reason is that you have a message variable in the deps array. If message was an empty string and then becomes "true" then you call useEffect twice. Just remove message from deps array of a useEffect.

Andrey Smolko
  • 712
  • 3
  • 8
0

It's difficult to diagnose exactly why your hook is running twice [1], but it's likely caused by StrictMode. StrictMode has an important job though [2] - I would recommend against removing it, and instead learning why it runs your effects twice.

React 18 remounts your components in development to help you find bugs. [3]

I would argue that because your code is responding to user input, it would be more appropriate to implement as an event handler rather than a useEffect [4]. Event handlers are easier to understand and maintain because they're guaranteed to only run once, as they aren't tied to the component lifecycle.

Brett
  • 16
  • 2