#How to send data from client to backend?

1 messages · Page 1 of 1 (latest)

safe mantle
#
"use client";

import { useInitDataRaw } from "@tma.js/sdk-react";
import { useRouter } from "next/navigation";

export default function Home() {
  const initDataRaw = useInitDataRaw();
  const router = useRouter();

  router.push('/welcome');
}

I have "use client" component where get the initData using hook. I have also api endpoint to handle this data and return a response depends on validation. How to send this data asynchronously there and handle response?

keen axleBOT
#

Hi @safe mantle. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

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();

  // Send data to the backend
  const sendData = async () => {
    const response = await fetch('/api/your-endpoint', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(initDataRaw)
    });

    // Handle response
    if (response.ok) {
      const data = await response.json();
      // Do something with the data
    } else {
      // Handle error
    }
  }

  // Call the function to send data
  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).

#

This information is based on general knowledge about Next.js and JavaScript, as the provided knowledge sources do not contain specific information about sending data from a client to the backend. For more detailed information, you can refer to the Next.js Documentation (https://nextjs.org/docs/api-routes/introduction) and the MDN Web Docs (https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch).

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@safe mantle kapa.ai is still learning and improving, please let us know how it did by reacting below

safe mantle
#

@keen axle initData contains some information about user (ID especially). After this response (in case if it's fulfilled) I need to check if user ID in database. And if it is - redirect him to /profile page, in case if not - redirect to /welcome page

keen axleBOT
#

Let me check the knowledge base for you. One moment! :books:

#

To achieve this, you can modify the sendData function to handle the response based on the user ID check. Here's an example:

"use client";

import { useInitDataRaw } from "@tma.js/sdk-react";
import { useRouter } from "next/router";

export default function Home() {
  const initDataRaw = useInitDataRaw();
  const router = useRouter();

  // Send data to the backend
  const sendData = async () => {
    const response = await fetch('/api/your-endpoint', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(initDataRaw)
    });

    // Handle response
    if (response.ok) {
      const data = await response.json();
      // Check if user ID exists in the database
      if (data.userIdExists) {
        router.push('/profile');
      } else {
        router.push('/welcome');
      }
    } else {
      // Handle error
    }
  }

  // Call the function to send data
  sendData();
}

In this example, it's assumed that the server responds with a JSON object that includes a userIdExists property, which is true if the user ID exists in the database and false otherwise. Based on this property, the user is redirected to either the /profile or /welcome page.

Please replace '/api/your-endpoint' with the path to your API endpoint and adjust the code according to the actual structure of your API response.

#

This information is based on general knowledge about Next.js and JavaScript, as the provided knowledge sources do not contain specific information about handling responses based on a user ID check. For more detailed information, you can refer to the Next.js Documentation (https://nextjs.org/docs/api-routes/introduction) and the MDN Web Docs (https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch).

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@safe mantle kapa.ai is still learning and improving, please let us know how it did by reacting below

safe mantle
#

@keen axle And also I need to check if in database (Mongo DB) already exists user with id (id is in initData)

keen axleBOT
#

Let me check the knowledge base for you. One moment! :books:

#

To check if a user with a specific ID already exists in your MongoDB database, you can use the findOne method in your API route. Here's an example of how you can do this:

import { connectToDatabase } from '../../lib/mongodb';

export default async function handler(req, res) {
  const { db } = await connectToDatabase();
  const user = await db.collection('users').findOne({ id: req.body.id });

  if (user) {
    // User exists
    res.status(200).json({ userIdExists: true });
  } else {
    // User does not exist
    res.status(200).json({ userIdExists: false });
  }
}

In this example, replace 'users' with the name of your users collection and connectToDatabase with your actual function for connecting to MongoDB. The findOne method tries to find a user with the specified ID in the database. If a user is found, the server responds with { userIdExists: true }, otherwise it responds with { userIdExists: false }.

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.

This information is based on general knowledge about Next.js and MongoDB, as the provided knowledge sources do not contain specific information about checking if a user ID exists in a MongoDB database. For more detailed information, you can refer to the Next.js Documentation (https://nextjs.org/docs/api-routes/introduction) and the MongoDB Node.js Driver Documentation (https://mongodb.github.io/node-mongodb-native/4.1/).

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@safe mantle kapa.ai is still learning and improving, please let us know how it did by reacting below

safe mantle
#

@keen axle how to make this code build without errors?

import prisma from "@/lib/prisma";
import { useInitData } from "@tma.js/sdk-react";

export default async function Profile() {
  const initData = useInitData();
  const user = await prisma.user.findUnique({
    where: {
      telegramId: initData?.user?.id
    }
  })

  return (
    <pre>
      <code style={{ color: "lightblue" }}>
        {JSON.stringify(user, null, 2)}
      </code>
    </pre>
  );
}