I currently have 2 state variables defined like so:
export const chatsAtom = atomFamily<Chat, string>({
key: 'chatsAtom',
default: undefined
})
export const chatIdsAtom = atom<string[]>({
key: 'chatIdsAtom',
default: []
})
I'm using useRecoilCallback()
to add and update the values:
const addChat = useRecoilCallback(
({set}) =>
(chat:Chat) => {
set(chatsAtom(chat.id), chat)
set(chatIdsAtom, prev => [...prev, chat.id])
}
)
Storing chats in a normal atom
means I can sort using setState(prev => [...prev].sort())
My question is, seeing as there is no get
method exposed by useRecoilCallback()
, how can I implement something similar using the atomFamily
and chat IDs?
More specifically, I want to be able to sort the most recently active chats to the top of my chat list. Meaning sorting by the most recent timestamp.
To achieve this, implementing it directly within the
useRecoilCallback()
function is challenging due to the absence of the get method exposed byuseRecoilCallback()
. However, an alternative approach is available rather than attempting a direct implementation withinuseRecoilCallback()
.The simplest method involves creating a new atom with the necessary information for sorting the chat list, instead of managing chats using
chatsAtom
. By creating a new atom and performing sorting and filtering within it, you can achieve the desired functionality.In the above code, a selector is used to create
sortedChatsAtom
. This atom retrieves chat IDs fromchatIdsAtom
, fetches each chat fromchatsAtom
, and returns a sorted list based on the latest timestamp.By using
useRecoilValue(sortedChatsAtom)
, you can easily access the sorted chat list.