React SWR
SWR là chiến lược trước tiên trả về dữ liệu từ bộ đệm (cũ), sau đó gửi yêu cầu tìm nạp (xác thực lại) và cuối cùng là dữ liệu cập nhật .SWR sẽ giúp cho ứng dụng của chúng ta chạy 1 cách mượt mà hơn giảm độ trễ
Cài đặt trên react với lệnh
npm instal swr
Tiếp theo chúng ta demo 1 app .Ở đây mình viết dạng component cho các bạn hiểu sâu hơn về React đó chính là farmwork dựa trên nền tảng component
Ở file src/api/Server.ts
export const fetcher = (url:any) =>fetch(url).then((res)=>res.json());
File src/component/ListPost.tsx
import React from "react";
import useSWR from "swr";
import {fetcher} from "../api/Server";
import {memo} from "react";
function ListPost(){
let url = 'https://dev.truyenvideo.com/api/post';
const {data ,error ,isLoading} = useSWR('https://dev.truyenvideo.com/api/post',fetcher);
if (isLoading){ return <div>Loading</div>}
if (error){return <div> Lỗi </div>}
return (
<>
{data.data.map((item:any)=>{
return(
<>
<li className="title" key={item.title}>{item.title}</li>
</>
);
})}
</>
)
}
export default memo(ListPost);
Tiếp theo ở file src/App.tsx
import {Suspense, useState} from 'react'
import './App.css'
import ListPost from "./component/ListPost";
function App() {
return (
<div className="App">
<Suspense>
<ListPost />
</Suspense>
</div>
)
}
export default App
Và bây giờ chúng ta chạy lệnh
npm run dev
để chạy app