webapp/src/context/inbox.tsx

52 lines
1.4 KiB
TypeScript
Raw Normal View History

2022-11-30 15:25:02 +00:00
import type { Accessor, JSX } from 'solid-js'
import { createContext, createSignal, useContext } from 'solid-js'
import type { Chat } from '../graphql/types.gen'
2022-11-24 15:39:31 +00:00
import { apiClient } from '../utils/apiClient'
import { createStore } from 'solid-js/store'
type InboxContextType = {
2022-11-30 15:25:02 +00:00
chats: Accessor<Chat[]>
2022-11-24 15:39:31 +00:00
actions: {
2022-11-27 05:49:48 +00:00
createChat: (members: string[], title: string) => Promise<void>
2022-11-30 15:25:02 +00:00
loadChats: () => Promise<void>
2022-11-24 15:39:31 +00:00
}
}
const InboxContext = createContext<InboxContextType>()
export function useInbox() {
return useContext(InboxContext)
}
export const InboxProvider = (props: { children: JSX.Element }) => {
2022-11-30 15:25:02 +00:00
const [chats, setChats] = createSignal<Chat[]>([])
const loadChats = async () => {
try {
2022-12-01 03:26:44 +00:00
const newChats = await apiClient.getChats({ limit: 50, offset: 0 })
2022-11-30 15:25:02 +00:00
setChats(
2022-12-01 03:26:44 +00:00
newChats.sort((x, y) => {
2022-11-30 15:25:02 +00:00
return x.updatedAt < y.updatedAt ? 1 : -1
})
)
} catch (error) {
console.log(error)
}
}
2022-11-24 15:39:31 +00:00
2022-11-27 05:49:48 +00:00
const createChat = async (members: string[], title: string) => {
const chat = await apiClient.createChat({ members, title })
2022-11-30 15:25:02 +00:00
setChats((prevChats) => {
return [chat, ...prevChats]
2022-11-25 07:36:45 +00:00
})
2022-11-25 23:34:46 +00:00
return chat
2022-11-24 15:39:31 +00:00
}
const actions = {
2022-11-30 15:25:02 +00:00
createChat,
loadChats
2022-11-24 15:39:31 +00:00
}
2022-11-27 05:49:48 +00:00
2022-11-30 15:25:02 +00:00
const value: InboxContextType = { chats, actions }
2022-11-24 15:39:31 +00:00
return <InboxContext.Provider value={value}>{props.children}</InboxContext.Provider>
}