Auto save post in regular interval by using custom hook in nextjs 13

Import useEffect from "react":

import { useEffect } from "react";

This line imports the useEffect function from the "react" library, which is a hook used to perform side effects in functional components.

Create a custom hook useFormSubmitInterval:

function useFormSubmitInterval(intervalMs: number): void {
  // ...
}

This function is a custom hook named useFormSubmitInterval, and it takes one argument intervalMs, which is the interval duration in milliseconds. It returns void, indicating that it doesn't return any value.

Inside the useEffect hook:

useEffect(() => {
  // ...
}, [intervalMs]);

This is where the main logic of the custom hook resides. The useEffect hook is used to perform actions when the component mounts or when the intervalMs value changes.

Set up an interval to submit the form:

const formSubmitInterval = setInterval(() => {
  const submitButton = document.querySelector('button[type="submit"]');

Here, you create an interval using setInterval that executes a function repeatedly at the specified interval. Inside this function, you attempt to find a submit button in the DOM with the attribute type="submit" using document.querySelector.

Check if a submit button was found:

if (submitButton) {
  // Simulate a click event on the submit button
  (submitButton as HTMLButtonElement).click();
}

If a submit button is found (submitButton is not null or undefined), it simulates a click event on the button. This effectively triggers the form submission as if the user had clicked the submit button manually.

Cleanup the interval on unmount:

return () => {
  clearInterval(formSubmitInterval);
};

The return statement defines a cleanup function that will be called when the component unmounts. This function clears the interval using clearInterval to prevent memory leaks.

Dependency array [intervalMs]:

The useEffect hook has a dependency array [intervalMs], which means that the effect will run whenever the intervalMs prop changes. This allows you to update the interval duration dynamically based on changes in the intervalMs prop.

Here is complete custom hook:

import { useEffect } from "react";


function useFormSubmitInterval(intervalMs: number): void {
  useEffect(() => {
    const formSubmitInterval = setInterval(() => {
      const submitButton = document.querySelector('button[type="submit"]');
      if (submitButton) {
        // Simulate a click event on the submit button
        (submitButton as HTMLButtonElement).click();
      }
      // You can add a condition here to handle the case when submitButton is null.
    }, intervalMs);

    return () => {
      clearInterval(formSubmitInterval);
    };
  }, [intervalMs]);
}
export default useFormSubmitInterval;

Call the hook where you have form with submit and want to use this custom hook

  // = = = = = = = = =  = = =
  // AUTO SAVE DRAFT
  // = = = = = = = = =  = = =
  const intervalMs = 5 * 60 * 1000; // 2 minutes
  useFormSubmitInterval(intervalMs);


Join & Grow

Be Part of a Winning Community!
Let’s Connect, learn, and succeed with like-minded people. Follow now!

Thanks for checking out my portfolio!

I really enjoy programming—it's not just my job, it's something I love. I've finished lots of web projects using different tools, and I'm excited to share what I know with everyone and help out.

I know my way around ReactJS, NextJS, MongoDB, WordPress, Laravel, CodeIgniter, and making things look good (UI/UX). I'm also a quick learner, always ready to learn and grow in my field.

If you've got any questions or need some help, feel free to get in touch anytime.

Best Regards,

SANDIPAN DASFull Stack Web Developer

Let‘s collaborate
on your next project

Chat on WhatsApp
Schedule a Zoom Meeting
Schedule a Zoom Meeting