skip to Main Content

My goal is to run a mutation as soon page loads and update the page when the mutation is complete, i.e. This is what I am trying at the moment:

useEffect(() => {
  void trpc.generateArticle.useMutation();
}, []);

The problem is that useEffect() runs twice when in development mode.

I understand why – it is covered in this Stack Overflow question.

However, I don’t understand what is the proper way to implement this pattern (starting mutation as soon as page loads) if I am not supposed to use useEffect here.

How to run mutation on page load in Next.js and run it only once?

2

Answers


  1. import trpc from 'your-trpc-library'; // Import your TRPC library
    
    export default function YourPage({ data }) {
      // Your component
    
      return (
        // Your JSX 
      );
    }
    
    export async function getServerSideProps() {
      try {
        //Run the mutation
        await trpc.generateArticle.useMutation();
      } catch (error) {
        console.error('Mutation failed:', error);
      }
    
      return {
        props: {
          data: 'Initial Data',
        },
      };
    }
    Login or Signup to reply.
  2. import { useEffect } from 'react';
    import trpc from 'your-trpc-library'; // Import your TRPC library
    
    function usePageLoadMutation() {
      useEffect(() => {
        const fetchData = async () => {
          try {
            // Run the mutation
            await trpc.generateArticle.useMutation();
          } catch (error) {
            console.error('Mutation failed:', error);
          }
        };
    
        fetchData();
      }, []);
    }
    
    export default function YourPage() {
      usePageLoadMutation();
    
      // Render your component as before
    }
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search