如何通过Fetch API获取最新添加的记录
问题描述
我希望在用户向API提交信息后,通过Fetch API获取最新添加的记录,并在后续页面作为回执展示。我认为最简单的方式是获取最新添加的数据行,例如目标report_id为3的记录(report_id为唯一自增字段)。
当前我的JavaScript代码如下:
const fakeUserId = 1; function fetchReport() { return fetch('http://localhost:8888/api/problems') .then(response => response.json()) .then(data => { console.log(data.data); }) } fetchReport();
接口返回的日志输出为:
{ "data": [ { "report_id": 1, "user_id": 1, "name": "Name1", "phone": "123" }, { "report_id": 2, "user_id": 2, "name": "Name2", "phone": "1234" }, { "report_id": 3, "user_id": 3, "name": "Name3", "phone": "12345" } ] }
请问该如何实现此需求,或是有其他更优方案?
解决方案
方案一:基于现有接口的前端处理
如果暂时没法修改后端API,你可以利用report_id自增的特性,在前端拿到全量数据后,筛选出ID最大的那条记录——它就是最新添加的。
修改你的fetchReport函数即可实现:
const fakeUserId = 1; function fetchReport() { return fetch('http://localhost:8888/api/problems') .then(response => { // 先判断请求是否成功,避免后续报错 if (!response.ok) throw new Error('请求数据失败'); return response.json(); }) .then(data => { // 用reduce遍历找到report_id最大的记录 const latestReport = data.data.reduce((prevItem, currentItem) => { return prevItem.report_id > currentItem.report_id ? prevItem : currentItem; }); console.log('最新提交的记录:', latestReport); // 这里可以把latestReport渲染到页面,作为回执展示 return latestReport; }) .catch(error => console.error('获取数据出错:', error)); } fetchReport();
如果你的场景是只需要当前用户提交的最新记录,还可以结合user_id做二次筛选:
// 先筛选出当前用户的所有记录 const userReports = data.data.filter(item => item.user_id === fakeUserId); // 再找其中ID最大的那条 const latestUserReport = userReports.reduce((prev, current) => prev.report_id > current.report_id ? prev : current, userReports[0]);
方案二:优化后端API(更优方案)
前端全量拉取数据的方式有个明显缺陷:数据量越大,带宽和性能浪费越严重。更合理的做法是从后端API层面优化,有两种推荐方式:
- 新增获取最新记录的接口:比如
GET /api/problems/latest,后端直接返回单条最新记录,前端只需请求这个接口就能拿到目标数据; - 提交请求后直接返回创建的记录:这是最推荐的方案——用户提交数据的POST请求响应里,直接返回刚创建的完整记录,前端无需额外请求就能拿到回执数据。
示例代码如下:
function submitReport(reportData) { return fetch('http://localhost:8888/api/problems', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(reportData) }) .then(response => { if (!response.ok) throw new Error('提交失败'); return response.json(); }) .then(createdReport => { // 这里直接拿到刚提交的记录,直接用来渲染回执 console.log('刚提交的记录:', createdReport); return createdReport; }); } // 调用示例:提交后直接展示回执 submitReport({ user_id: 1, name: '测试用户', phone: '13800138000' }) .then(report => { document.getElementById('receipt-container').innerHTML = ` <h3>提交成功!</h3> <div class="receipt-item">姓名:${report.name}</div> <div class="receipt-item">电话:${report.phone}</div> <div class="receipt-item">记录ID:${report.report_id}</div> `; });
这种方式不仅高效,还能避免多用户同时提交时,前端拉取全量数据可能出现的同步误差。
内容的提问来源于stack exchange,提问作者user9294038
相关产品推荐
相关产品推荐

