fix: use composing atom to switch between cache and local storage
This commit is contained in:
parent
2b0a4c433c
commit
1395aa40eb
@ -6,7 +6,7 @@ import {
|
|||||||
} from '@janhq/core'
|
} from '@janhq/core'
|
||||||
import { atom } from 'jotai'
|
import { atom } from 'jotai'
|
||||||
|
|
||||||
import { atomWithStorage, createJSONStorage } from 'jotai/utils'
|
import { atomWithStorage } from 'jotai/utils'
|
||||||
|
|
||||||
import {
|
import {
|
||||||
getActiveThreadIdAtom,
|
getActiveThreadIdAtom,
|
||||||
@ -16,17 +16,23 @@ import {
|
|||||||
import { TokenSpeed } from '@/types/token'
|
import { TokenSpeed } from '@/types/token'
|
||||||
|
|
||||||
const CHAT_MESSAGE_NAME = 'chatMessages'
|
const CHAT_MESSAGE_NAME = 'chatMessages'
|
||||||
const storage = createJSONStorage<Record<string, ThreadMessage[]>>(
|
|
||||||
() => sessionStorage
|
|
||||||
)
|
|
||||||
/**
|
/**
|
||||||
* Stores all chat messages for all threads
|
* Stores all chat messages for all threads
|
||||||
*/
|
*/
|
||||||
export const chatMessages = atomWithStorage<Record<string, ThreadMessage[]>>(
|
export const chatMessagesStorage = atomWithStorage<
|
||||||
CHAT_MESSAGE_NAME,
|
Record<string, ThreadMessage[]>
|
||||||
{},
|
>(CHAT_MESSAGE_NAME, {}, undefined, { getOnInit: true })
|
||||||
storage,
|
|
||||||
{ getOnInit: true }
|
export const cachedMessages = atom<Record<string, ThreadMessage[]>>()
|
||||||
|
/**
|
||||||
|
* Retrieve chat messages for all threads
|
||||||
|
*/
|
||||||
|
export const chatMessages = atom(
|
||||||
|
(get) => get(cachedMessages) ?? get(chatMessagesStorage),
|
||||||
|
(_get, set, newValue: Record<string, ThreadMessage[]>) => {
|
||||||
|
set(cachedMessages, newValue)
|
||||||
|
;(() => set(chatMessagesStorage, newValue))()
|
||||||
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user