To send data from a client component to the backend in Next.js, you can use the fetch API to make an asynchronous request. Here's a basic example of how you can do this:
"use client";
import { useInitDataRaw } from "@tma.js/sdk-react";
import { useRouter } from "next/navigation";
export default function Home() {
const initDataRaw = useInitDataRaw();
const router = useRouter();
const sendData = async () => {
const response = await fetch('/api/your-endpoint', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(initDataRaw)
});
if (response.ok) {
const data = await response.json();
} else {
}
}
sendData();
router.push('/welcome');
}
In this example, replace '/api/your-endpoint' with the path to your API endpoint. The fetch function sends a POST request to the specified endpoint with initDataRaw as the request body. The response from the server is then handled based on its status.
Please note that this is a basic example and you might need to adjust it based on your specific requirements and the structure of your API.
Also, remember that the fetch function returns a Promise that resolves to the Response object representing the response to the request. This response object is not the actual JSON. To extract the JSON body content from the response, we use the json() method (which also returns a Promise).