I'm working on a Next.js 13 project and have implemented a functionality that allows users to generate images based on their input. The image generation process is handled by the generateImage function, and it successfully generates the image and stores it in the image state.
However, I'm facing an issue when trying to automatically redirect the user to a new page (/display-image) immediately after the image is generated. I want users to be able to view the generated image without having to manually trigger the navigation.
I have tried using the redirect function from next/navigation to perform the navigation, but I encountered the error "NextRouter was not mounted."
Here's the code block for the implementation:
import { PageWrapper } from '@/components/Page-Wrapper';
import Image from 'next/image';
import { useRouter } from 'next/navigation';
import React, { useEffect, useState } from 'react';
export default function Page() {
const [searchVal, setSearchVal] = useState('');
const [loading, setLoading] = useState(false);
const [image, setImage] = useState('');
async function generateImage(): Promise<any> {
setLoading(true);
const response = await fetch(`/api/generate`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
prompt: `${searchVal}`,
}),
});
const data = await response.json();
setImage(data.url);
setSearchVal('');
setLoading(false);
}
const router = useRouter();
useEffect(() => {
if (image) {
// Redirect to the new page after generating the image
router.push(`/display-image?image=${encodeURIComponent(image)}`);
}
}, [image, router]);
return (
<PageWrapper>
<div>
<main className='py-40 px-8 md:px-12 lg:px-24 flex flex-col items-center justify-center'>
<h1 className='text-center text-5xl md:text-6xl lg:text-7xl font-bold tracking-tight mb-4'>
Type Your Prompt
</h1>
<Input
value={searchVal}
type='text'
onChange={(event: React.ChangeEvent<HTMLInputElement>) =>
setSearchVal(event.target.value)
}
className='max-w-md shadow focus:ring-zinc-500'
placeholder='Enter Name Here...'
/>
<button
onClick={() => generateImage()}
className={cn(
buttonVariants({ variant: 'default' }),
'flex items-center justify-center py-3 px-6 mt-6 '
)}
disabled={loading}
>
{loading ? 'Loading...' : 'Create Your Image'}
</button>
{image && (
<div className='mt-8'>
<Image
className='w-64 h-64 object-cover rounded-md shadow-lg'
src={image}
alt='AI Generated'
width={500}
height={500}
/>
</div>
)}
</main>
</div>
</PageWrapper>
);
}
I suspect that the issue might be related to how Next.js 13 handles routing and page transitions. I'm seeking guidance on how to properly implement the automatic redirection to the /display-image page after the image is successfully generated in Next.js 13. Any help would be greatly appreciated. Thank you!