axios-hookshỗ trợ liền mạch các tình huống kết xuất phía máy chủ, bằng cách tải trước dữ liệu trên máy chủ và cung cấp dữ liệu cho máy khách, do đó máy khách không cần phải tải lại.
Nó hoạt động như thế nào
cây thành phần React được hiển thị trên máy chủ
useAxiosYêu cầu HTTP được thực hiện trên máy chủ
mã máy chủ chờ serializeCache()để có được biểu diễn tuần tự hóa của bộ đệm yêu cầu-phản hồi
máy chủ đưa phiên bản bộ nhớ đệm được tuần tự hóa JSON vào một windowbiến toàn cục
máy khách hydrat hóa bộ nhớ đệm từ biến toàn cục trước khi hiển thị ứng dụng bằng cách sử dụngloadCache
— Example 5
Đây ta thấy chúng hỗ trợ server side Rendering đây.
pages\index.tsx
import { GetServerSideProps } from "next";
import axiosInstance from "../utils/axiosInstance";
import useAxios from "axios-hooks";
interface Post {
id: number;
title: string;
body: string;
}
interface Props {
initialData: Post[];
}
export default function Home({ initialData }: Props) {
// Sử dụng axios-hooks với dữ liệu đã fetch từ SSR
const [{ data, loading, error }] = useAxios<Post[]>("https://jsonplaceholder.typicode.com/posts", {
manual: false,
useCache: true
});
console.log(initialData)
if (loading) return <p>Loading...</p>;
if (error) return <p>Error loading posts</p>;
return (
<div>
<h1>Blog Posts</h1>
<ul>
{initialData?.map((post) => (
<li key={post.id}>
<h3>{post.title}</h3>
<p>{post.body}</p>
</li>
))}
</ul>
</div>
);
}
// Fetch dữ liệu từ server trước khi render trang
export const getServerSideProps: GetServerSideProps = async () => {
const { data } = await axiosInstance.get<Post[]>("/posts");
return {
props: {
initialData: data
},
};
};