useIndexedDB
注意
该hooks正在测试阶段,请谨慎在生产环境使用!
随着浏览器的功能不断增强,越来越多的网站开始考虑,将大量数据储存在客户端,这样可以减少从服务器获取数据,直接从本地获取数据。
现有的浏览器数据储存方案,都不适合储存大量数据:Cookie 的大小不超过4KB,且每次请求都会发送回服务器;LocalStorage 在 2.5MB 到 10MB 之间(各家浏览器不同),而且不提供搜索功能,不能建立自定义的索引。所以,需要一种新的解决方案,这就是 IndexedDB 诞生的背景。
通俗地说,IndexedDB 就是浏览器提供的本地数据库,它可以被网页脚本创建和操作。IndexedDB 允许储存大量数据,提供查找接口,还能建立索引。这些都是 LocalStorage 所不具备的。就数据库类型而言,IndexedDB 不属于关系型数据库(不支持 SQL 查询语句),更接近 NoSQL 数据库。
# add
import { useIndexedDB } from "cyl-hooks-tools/useIndexedDB"
export default function App() {
const { add } = useIndexedDB<{ name: string }>("test", "testStore")
const addData =async ()=>{
const data = await add(1,{name: "测试"})
console.log(data)
}
return (
<div>
<button onClick={addData}>增加</button>
</div>
)
}
# update
import { useIndexedDB } from "cyl-hooks-tools/useIndexedDB"
export default function App() {
const { update } = useIndexedDB<{ name: string }>("test", "testStore")
const updateDataById =async ()=>{
const data = await update(1,{name: "测试-update"})
console.log(data)
}
return (
<div>
<button onClick={updateDataById}>增加</button>
</div>
)
}
# get
import { useIndexedDB } from "cyl-hooks-tools/useIndexedDB"
export default function App() {
const { get } = useIndexedDB<{ name: string }>("test", "testStore")
const getDataById =async ()=>{
const data = await get(1)
console.log(data)
}
return (
<div>
<button onClick={getDataById}>增加</button>
</div>
)
}
# getAll
import { useIndexedDB } from "cyl-hooks-tools/useIndexedDB"
export default function App() {
const { getAll } = useIndexedDB<{ name: string }>("test", "testStore")
const getAllData =async ()=>{
const data = await getAll()
console.log(data)
}
return (
<div>
<button onClick={getAllData}>增加</button>
</div>
)
}
# remove
import { useIndexedDB } from "cyl-hooks-tools/useIndexedDB"
export default function App() {
const { remove,getAll } = useIndexedDB<{ name: string }>("test", "testStore")
const removeDataById =async ()=>{
await remove(1)
const data = await getAll()
console.log(data)
}
return (
<div>
<button onClick={removeDataById}>增加</button>
</div>
)
}
上次更新: 2023/05/08, 19:10:56