skip to Main Content

I want to get a value from client side and use it in server side,

But I don’t know how to use use State and I know there is no way to using useState in server side
So Is there any solution to use instead??!
In fact there is a url in serverside and I want to get the value from client side and use it in that url with ${}

2

Answers


  1. You can achieve your goal by passing the client-side value to the server through a request, query parameter, or API endpoint.

    Client side:

    import { useState } from 'react';
    
    const MyComponent = () => {
      const [myValue, setMyValue] = useState('');
    
      const handleSubmit = () => {
        fetch(`/api/myEndpoint?value=${encodeURIComponent(myValue)}`)
          .then((response) => response.json())
          .then((data) => {
            // Do something with the data from the server if needed
            console.log(data);
          })
          .catch((error) => {
            console.error('Error:', error);
          });
      };
    
      return (
        <div>
          <input value={myValue} onChange={(e) => setMyValue(e.target.value)} />
          <button onClick={handleSubmit}>Submit</button>
        </div>
      );
    };
    
    

    Server Side:

    export default function handler(req, res) {
      const { value } = req.query;
    
      // use the 'value' received from the client-side 
    
      res.status(200).json({ message: `Received value: ${value}` });
    }
    
    
    Login or Signup to reply.
  2. please try to explain a little be more what do you need to do with this information in server side
    and i will try to help you

    but if you need some data in server side
    you can send this with axios but it’s depends what do you want to do
    in server side like POST / GET / DELETE / PUT
    and according this i will help you to write the code

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search