Skip to content

Commit

Permalink
fix: save secret key per form with useQuery to prevent need for enter…
Browse files Browse the repository at this point in the history
…ing secret key (#5743)

fix: save secret key per form with useQuery

feature parity with angular
  • Loading branch information
darrelhong authored Feb 17, 2023
1 parent f632699 commit 606e656
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 3 deletions.
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
import { useEffect, useRef, useState } from 'react'
import { useCallback, useEffect, useRef } from 'react'
import { useQuery, useQueryClient } from 'react-query'
import { BroadcastChannel } from 'broadcast-channel'

import { useHasChanged } from '~hooks/useHasChanged'

import { adminFormResponsesKeys } from '../../queries'

const SECRETKEY_BROADCAST_KEY = 'formsg_private_key_sharing'

type SecretKeyBroadcastMessage =
Expand All @@ -17,7 +20,21 @@ type SecretKeyBroadcastMessage =
}

export const useSecretKey = (formId: string) => {
const [secretKey, setSecretKey] = useState<string>()
const { data: secretKey } = useQuery({
queryKey: adminFormResponsesKeys.secretKey(formId),
initialData: '',
})

const queryClient = useQueryClient()
const setSecretKey = useCallback(
(secretKey: string) =>
queryClient.setQueryData(
adminFormResponsesKeys.secretKey(formId),
secretKey,
),
[formId, queryClient],
)

const hasSecretKeyChanged = useHasChanged(secretKey)

// BroadcastChannel will only broadcast the message to scripts from the same origin
Expand Down Expand Up @@ -80,7 +97,7 @@ export const useSecretKey = (formId: string) => {
}
}
}
}, [secretKey, formId])
}, [secretKey, formId, setSecretKey])

return [secretKey, setSecretKey] as const
}
1 change: 1 addition & 0 deletions frontend/src/features/admin-form/responses/queries.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ export const adminFormResponsesKeys = {
},
individual: (id: string, submissionId: string) =>
[...adminFormResponsesKeys.id(id), 'individual', submissionId] as const,
secretKey: (id: string) => [...adminFormResponsesKeys.id(id), 'secretKey'],
}

export const adminFormFeedbackKeys = {
Expand Down

0 comments on commit 606e656

Please sign in to comment.