feat: server actions that run on request in server-side
Opened this issue · 0 comments
hulxv commented
Description
Introduce the concept of server actions to enable direct function execution on the server from the client side without needing to create traditional API routes. Developers can define server-side logic in their React components and call these server actions from the client.
Example
// ./src/pages/home.jsx
import { useAction } from 'metassr/hooks'; // Import the useAction hook from MetaSSR's node module
// Home page component
export default function Home() {
// Hook to fetch results from server actions
const { all, GET, POST, PUT, DELETE } = useAction();
// Example usage of action results
console.log('All actions:', all);
console.log('GET action result:', GET);
console.log('POST action result:', POST);
console.log('PUT action result:', PUT);
console.log('DELETE action result:', DELETE);
return (
<div>
<h1>Hello World</h1>
<p>Data from server actions will be logged in the console.</p>
</div>
);
}
// Default server action to handle general operations
export function action() {
// Perform operations on the server for any request
// Example logging message (will appear in server logs)
console.log('Executing default action on server');
const result = { message: 'Default action result' };
return result;
}
// Action for handling GET requests
export function action$GET() {
// Perform operations specific to GET requests
// Example logging message (will appear in server logs)
console.log('Executing GET action on server');
const result = { message: 'GET request result' };
return result;
}
// Action for handling POST requests
export function action$POST() {
// Perform operations specific to POST requests
// Example logging message (will appear in server logs)
console.log('Executing POST action on server');
const result = { message: 'POST request result' };
return result;
}
// Action for handling PUT requests
export function action$PUT() {
// Perform operations specific to PUT requests
// Example logging message (will appear in server logs)
console.log('Executing PUT action on server');
const result = { message: 'PUT request result' };
return result;
}
// Action for handling DELETE requests
export function action$DELETE() {
// Perform operations specific to DELETE requests
// Example logging message (will appear in server logs)
console.log('Executing DELETE action on server');
const result = { message: 'DELETE request result' };
return result;
}
Benefits
- Simplifies communication between the client and server by allowing server-side functions to be invoked directly from the client.
- Reduces boilerplate for API creation, making it easier to manage server-side logic within components.
- Improves data fetching and mutation patterns, leading to more seamless integration of server-side and client-side operations.