我有这个与反应应用程序一起使用,但我将项目移植到 next.js 并且由于某种原因它不起作用。我正在使用SWR
自定义挂钩:
import axios from "axios";
import useSwr from "swr";
export const useHttp = (url, token) => {
const fetcher = (url, token) =>
axios
.get(url, { headers: { Authorization: "Bearer " + token } })
.then((res) => res.data);
const { data, error } = useSwr(token ? [url, token] : null, fetcher);
return {
data: data,
isLoading: !error && !data,
isError: error,
};
};
在我的页面
const { data, isError, isLoading } = useHttp(
`http://localhost:8000/api/admin/bookings/${id}`,
session.user.servertoken
);
const deleteBooking = async (id) => {
//immediatly remove record from the screen before getting response from the server
mutate(
[
`http://localhost:8000/api/admin/bookings/${id}`,
session.user.servertoken,
],
data.filter((d) => d._id !== id),
false
);
try {
const response = await axios.delete(
`${process.env.NEXT_PUBLIC_API_ENDPOINT}/admin/bookings/${id}`,
{ headers: { Authorization: "Bearer " + session.user.servertoken } }
);
mutate([
`http://localhost:8000/api/admin/bookings/${id}`,
session.user.servertoken,
]);
} catch (err) {
console.log(err);
}
};
按钮:
<Button
variant="danger"
onClick={() => deleteBooking(d._id)}
>
Delete
</Button>
不过,在 ui 方面绝对没有任何反应(记录在数据库中已删除)。单击删除并运行 deleteBooking 功能后,该记录应从屏幕上消失。
*如果我将它添加到我的 deleteBooking 函数中,它会显示正确的数据:
const filteredData = data.filter((d) => d._id !== id);