Home > database >  useEffect is not working the way i expect it to
useEffect is not working the way i expect it to

Time:08-17

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();

CodePudding user response:

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.

CodePudding user response:

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.

CodePudding user response:

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> */
);
  • Related