Sort Recoil atoms in atomFamily using properties in each one

49 views Asked by At

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.

1

There are 1 answers

0
Kyle Choi On

To achieve this, implementing it directly within the useRecoilCallback() function is challenging due to the absence of the get method exposed by useRecoilCallback(). However, an alternative approach is available rather than attempting a direct implementation within useRecoilCallback().

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.

export const sortedChatsAtom = selector({
  key: 'sortedChatsAtom',
  get: ({ get }) => {
    const chatIds = get(chatIdsAtom);
    const sortedChats = chatIds.map(id => get(chatsAtom(id))).sort((a, b) => b.timestamp - a.timestamp);
    return sortedChats;
  }
});

In the above code, a selector is used to create sortedChatsAtom. This atom retrieves chat IDs from chatIdsAtom, fetches each chat from chatsAtom, and returns a sorted list based on the latest timestamp.

By using useRecoilValue(sortedChatsAtom), you can easily access the sorted chat list.