How to make an API request to an express server when clicking on value cells within a React Pivot Table?
Introduction
This article guides you through the process of making an API request to an Express server when clicking on value cells within a React Pivot Table. The demonstration covers two main scenarios: adding new data by clicking on an empty cell and deleting existing data by clicking on a cell that contains values. In this article, we use the Node.js Express server to perform these operations. However, you can adapt it to any web server to meet your specific requirements.
Setting up the client-side (React application - App.js)
In your React application, you will need to use a cellClick event to manage value cell interactions in your pivot table. This event is triggered when a cell in the pivot table is clicked, and it’s perfect for initiating API request.
Below is a code example of how you can send a POST request to the server with relevant cell information and the current data source:
[App.js]
import { PivotViewComponent } from '@syncfusion/ej2-react-pivotview';
import { useState } from 'react';
// Example Pivot Table component with the cellClick event handler
function App() {
let pivotObj;
// State initialization for holding data source
const [datas, setDatas] = useState(pivotData);
// The event handler for cell clicks
async function cellSelecting(args) {
if (args.data.axis == 'value') {
let data = args.data;
// POST request to your server
const response = await fetch("http://localhost:5000/data", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
// Passed the cell information and data source to the server here.
body: JSON.stringify({ data, pivotData: datas }),
})
// Get the response from the server here. Here we have returned updated data as a response.
const res = await response.json();
// Assign the updated data to the pivot table.
pivotObj.dataSourceSettings.dataSource = res;
// Also update the state variable in which the data is stored.
setDatas(res);
} else{
// Cancel cell click event for non-value cells(i.e., row and column headers)
args.cancel = true;
}
}
// Render the Pivot Table component with the cellClick event bound
return (
<PivotViewComponent
ref={(scope) => {
pivotObj = scope;
}}
cellClick={cellSelecting.bind(this)}
// Additional pivot table configuration...
/>
);
};
export default App;
Configuring the server-side (Express server - index.js)
On the server-side, you will need to create an API endpoint that can receive data from the client-side (i.e., App.js) when a pivot table value cell is clicked. Here’s a code example of how a simple Express server could handle the Pivot Table API request:
[index.js]
// Middleware for parsing JSON and handling CORS
import express from 'express';
import cors from 'cors';
const app = express();
app.use(express.json());
app.use(cors());
// Endpoint to handle updates to the pivot table data
app.use("/data", (req,res) => {
try{
console.log(req.body);
let dataFromReact=req.body;
// Delete the specific raw data of the cells from the data source if we have data in the cell.
if(dataFromReact.data.value>0){
dataFromReact.pivotData.splice(Object.keys(dataFromReact.data.indexObject),1);
res.status(200).send(dataFromReact.pivotData);
} else{
// Added the raw data based on the cell combinations to the pivot table if the cell is empty.
let newData={
"Sold": 40,
"Country": dataFromReact.data.rowHeaders,
"Year": dataFromReact.data.columnHeaders
};
dataFromReact.pivotData.push(newData);
// Send back the updated data source to the client
res.status(200).send(dataFromReact.pivotData);
}
} catch (error) {
res.status(400).send(error);
}
});
// Define the port for the server here.
app.listen(5000,()=>{
console.log("Server is running on port 5000");
});
Implementation notes
- Upon clicking a value cell in the pivot table, the cellClick event is triggered.
- Inside this event method, we make an API request to the Express server (i.e., index.js file) with the relevant cell data and the current data source of the pivot table.
- On the Express server, we process requests from the client-side application (i.e., App.js). If the clicked cell has a value, we delete the corresponding data record from the data source; if it’s empty, we create a new record based on the provided cell information and update the data source.
- Then, we send back the updated data source to the client-side application.
- In the client-side application, we update the data source in both the pivot table and the React
useState
hook holding the pivot data.
The following GIF image portrays the results of the code snippet mentioned above.
GIF
Conclusion
By following these steps, you can easily make an API request to an Express server when clicking on value cells within a React Pivot Table. Such implementations can greatly enhance the interactivity of your application, allowing you to perform dynamic data operations based on user interactions with the pivot table. Remember to handle server-side operations securely, manage errors properly, and always test your endpoints to ensure reliable performance.
You can refer to our React Pivot Table feature tour page to learn about its other groundbreaking feature representations and documentation, and how to quickly get started for configuration specifications. You can also explore our React Pivot Table example to understand how to create and manipulate data.
For current customers, you can check out our components on the License and Downloads page. If you are new to Syncfusion, you can try our 30-day free trial to check out our other controls.
If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forums, support portal, or feedback portal. We are always happy to assist you!