search

Home  >  Q&A  >  body text

Is there a way to use useState in Next.js server-side rendering?

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

But I don't know how to use useState, and I know there is no way to use useState on the server side So is there any other solution that can be used instead? ! Actually, there is a url on the server side and I want to get the value from the client and use ${} in that url.

P粉245489391P粉245489391332 days ago427

reply all(1)I'll reply

  • P粉481366803

    P粉4813668032024-02-18 18:15:16

    You can achieve your goal by passing client-side values ​​to the server via requests, query parameters, or API endpoints.

    Client:

    import { useState } from 'react';
    
    const MyComponent = () => {
      const [myValue, setMyValue] = useState('');
    
      const handleSubmit = () => {
        fetch(`/api/myEndpoint?value=${encodeURIComponent(myValue)}`)
          .then((response) => response.json())
          .then((data) => {
            // 如果需要,可以对从服务器返回的数据进行处理
            console.log(data);
          })
          .catch((error) => {
            console.error('Error:', error);
          });
      };
    
      return (
        <div>
          <input value={myValue} onChange={(e) => setMyValue(e.target.value)} />
          <button onClick={handleSubmit}>提交</button>
        </div>
      );
    };

    Service-Terminal:

    export default function handler(req, res) {
      const { value } = req.query;
    
      // 使用从客户端接收到的'value'
    
      res.status(200).json({ message: `接收到的值:${value}` });
    }

    reply
    0
  • Cancelreply