1+ import type {
2+ DevicesGetParams ,
3+ DevicesUpdateBody ,
4+ SeamHttpApiError ,
5+ } from '@seamapi/http/connect'
6+ import type { Device } from '@seamapi/types/connect'
7+ import {
8+ useMutation ,
9+ type UseMutationResult ,
10+ useQueryClient ,
11+ } from '@tanstack/react-query'
12+
13+ import { NullSeamClientError , useSeamClient } from 'lib/seam/use-seam-client.js'
14+
15+ export type UseSetDeviceNameParams = never
16+
17+ export type UseSetDeviceNameData = undefined
18+
19+ export type UseSetDeviceNameMutationVariables = Pick < DevicesUpdateBody , 'device_id' | 'name' >
20+
21+ type MutationError = SeamHttpApiError
22+
23+ export function useSetDeviceName ( params : DevicesGetParams ) : UseMutationResult <
24+ UseSetDeviceNameData ,
25+ MutationError ,
26+ UseSetDeviceNameMutationVariables
27+ > {
28+ const { client } = useSeamClient ( )
29+ const queryClient = useQueryClient ( )
30+
31+ return useMutation <
32+ UseSetDeviceNameData ,
33+ MutationError ,
34+ UseSetDeviceNameMutationVariables
35+ > ( {
36+ mutationFn : async ( variables ) => {
37+ if ( client === null ) throw new NullSeamClientError ( )
38+ await client . devices . update ( variables )
39+ } ,
40+ onSuccess : ( _data , variables ) => {
41+
42+ queryClient . setQueryData < Device | null > (
43+ [ 'devices' , 'get' , params ] ,
44+ ( device ) => {
45+ if ( device == null ) {
46+ return
47+ }
48+
49+ return getUpdatedDevice ( device , variables . name ?? device . properties . name )
50+ }
51+ )
52+
53+ queryClient . setQueryData < Device [ ] > (
54+ [ 'devices' , 'list' , { device_id : variables . device_id } ] ,
55+ ( devices ) : Device [ ] => {
56+ if ( devices == null ) {
57+ return [ ]
58+ }
59+
60+ return devices . map ( ( device ) => {
61+ if ( device . device_id === variables . device_id ) {
62+ return getUpdatedDevice ( device , variables . name ?? device . properties . name )
63+ }
64+
65+ return device
66+ } )
67+ }
68+ )
69+ } ,
70+ } )
71+ }
72+
73+ const getUpdatedDevice = ( device : Device , name : string ) : Device => {
74+ const { properties } = device
75+
76+ return {
77+ ...device ,
78+ properties : {
79+ ...properties ,
80+ name,
81+ } ,
82+ }
83+ }
0 commit comments