I'm trying to fetch some data from an API and based on this response redirect to a page.
App flow is:
User Click a button --> Button call a function --> Function fetch data from API and redirect to a new URL based on the fetched data.
components/Start.js
import { setCookie } from "nookies";
export default function Start() {
return (
<button className="text-2xl font-bold" onClick={CreateAPI}>
Start →
</button>
);
}
async function CreateAPI() {
const res = await fetch(`https://**********/create`);
const data = await res.json();
if (!data) {
return {
redirect: {
destination: "/maintenance",
permanent: false,
},
};
}
console.log(data);
setCookie(null, "owner", "true", {
maxAge: 3600,
path: "/",
});
return {
redirect: {
destination: `/${data}`,
permanent: false,
},
};
}
index.js
import Head from 'next/head'
import Start from '../components/Start'
export default function Home() {
return (
<div className="flex flex-col items-center justify-center min-h-screen py-2">
<Head>
<title>xxx</title>
</Head>
<main className="flex flex-col items-center justify-center w-full flex-1 px-20 text-center">
<h1 className="text-6xl font-bold">
Welcome
</h1>
<div className="flex flex-wrap items-center justify-around max-w-4xl mt-6 sm:w-full">
<a
className="p-6 mt-6 text-center border w-96 rounded-xl hover:text-blue-600 focus:text-blue-600"
>
<Start />
</a>
</div>
</main>
When I click the button I can see the data on the console, however the redirect is not happening.
If you can point on the right direction would be really helpful.
Thanks