Files
supabase/apps/studio/hooks/misc/useLocalStorage.ts
2ce7f1f33c experiment(studio): expanded onboarding survey (#45707)
Adds an optional onboarding survey to the new-organization form, so we
learn who new orgs are for and what they are building. Users in the
`org_form` arm of the `onboardingSurveyPlacement` PostHog flag see a
**Help improve Supabase** section. Users in `control` get today's form
unchanged and still record exposure, so the two arms can be compared;
users the flag doesn't assign get the existing form and record nothing.

**Changed:**
- **Survey on the new-org form**: asks **Who is this org for?** (plus
**How many people?** for companies) and **What are you building?** (AI
assistant or agent, AI search or knowledge base, B2B SaaS, internal
tool, consumer app, social or community, marketplace or booking,
e-commerce, developer tool or app builder, analytics or reporting,
other). Every question ends with **Prefer not to say**. Answers go to
`POST /platform/organizations/onboarding-survey` as `kind`, `size` and
`building`.
- **Follow-up card for a blank survey**: if the creator answers nothing,
a card in the bottom-right asks the same questions for 5 minutes after
the org is created (not on project creation pages). Only the creator
sees it, once, tracked in localStorage. A blank form sends nothing at
creation, because the platform keeps only the first survey response per
user and org. Skipping the card, closing it, or letting the 5 minutes
run out still saves the org type and size picked on the form.
- **Telemetry**: exposure for both arms, plus submit, submit failed,
dismissed (including `follow_up_expired` when the card times out) and
Answer clicked events with `surface` set to `org_form` or `follow_up`.

**Note:** I cut **How comfortable are you working with code?** from v1.
The survey endpoint doesn't accept `coding_experience` yet, and the
question is planned to move to the user level later.

## To test
Setup: override `onboardingSurveyPlacement` to `org_form` in the dev
toolbar. Close the Terms of Service banner first, since the follow-up
card shares its slot.

Tested on the PR preview:
- [x] Create an org with **Who is this org for?** and **What are you
building?** answered, expect one `POST
/platform/organizations/onboarding-survey` carrying `kind` and
`building` (plus `size` for companies), no `coding_experience` key, and
no `kind` or `size` in the org-create request. Observed: 204 with
`{"slug":"<slug>","kind":"COMPANY","size":"10","building":"b2b_saas"}`;
org-create body was `{"name":"<name>","tier":"tier_free"}`
- [x] Create an org with the survey left blank, then open its projects
page, expect the follow-up card; answer it, expect the same survey
request and a "Thanks for sharing" toast. Observed: no survey request at
creation; after answering, 204 with
`{"slug":"<slug>","kind":"PERSONAL","building":"consumer_app"}` and the
toast
- [x] Override to `control`, open the new-org form, expect the same form
as master (Name, Type, Company size with "How many people are in your
company?" for Company, then Plan), no survey section, and an
`onboarding_survey_placement_experiment_exposed` event with `variant:
control`. Observed: screenshots match master's form field for field; the
exposure arrived in PostHog with `variant: control`
- [x] Create an org with the survey left blank and don't act on the
follow-up card for 5 minutes, expect the card to disappear, one `POST
/platform/organizations/onboarding-survey` carrying the form's `kind`
(plus `size` for companies) and no `building`, and an
`onboarding_survey_dismissed` event with `reason: follow_up_expired`.
Observed (stored follow-up time moved to near expiry instead of
waiting): the card disappeared at the 5-minute mark with one 204
carrying `{"slug":"<slug>","kind":"AGENCY"}` and the `follow_up_expired`
event; an already-expired follow-up sends on page load; with the dialog
open past expiry nothing is sent until it is closed

## Linear
- fixes GROWTH-771
- part of GROWTH-1463

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
Co-authored-by: Jonathan Summers-Muir <MildTomato@users.noreply.github.com>
Co-authored-by: Pamela Chia <pamelachiamayyee@gmail.com>
Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com>
2026-11-10 17:52:57 +09:00

100 lines
3.7 KiB
TypeScript

// Reference: https://usehooks.com/useLocalStorage/
import { useQuery, useQueryClient } from '@tanstack/react-query'
import { safeLocalStorage } from 'common'
import { Dispatch, SetStateAction, useCallback, useMemo, useState } from 'react'
export function useLocalStorage<T>(key: string, initialValue: T) {
// State to store our value
// Pass initial state function to useState so logic is only executed once
const [storedValue, setStoredValue] = useState<T>(() => {
// safeLocalStorage handles SSR and unavailable storage (returns null);
// the try/catch here only guards JSON.parse against corrupt values.
const item = safeLocalStorage.getItem(key)
try {
return item ? (JSON.parse(item) as T) : initialValue
} catch (error) {
console.warn(`Failed to parse localStorage value for "${key}"`, error)
return initialValue
}
})
// Return a wrapped version of useState's setter function that ...
// ... persists the new value to localStorage.
const setValue = useCallback(
(value: T | ((val: T) => T)) => {
// Allow value to be a function so we have same API as useState
const valueToStore = value instanceof Function ? value(storedValue) : value
// Save state
setStoredValue(valueToStore)
// Persist (safeLocalStorage swallows storage errors internally)
safeLocalStorage.setItem(key, JSON.stringify(valueToStore))
},
[key, storedValue]
)
return [storedValue, setValue] as const
}
/** Query key `useLocalStorageQuery` caches `key` under, for writes made outside the hook. */
export const getLocalStorageQueryKey = (key: string) => ['localStorage', key]
/**
* Hook to load/store values from local storage with an API similar
* to `useState()`.
*
* Differs from `useLocalStorage()` in that it uses `react-query` to
* invalidate stale values across hooks with the same key.
*/
export function useLocalStorageQuery<T>(key: string, initialValue: T) {
const queryClient = useQueryClient()
const queryKey = useMemo(() => getLocalStorageQueryKey(key), [key])
const {
error,
data: storedValue = initialValue,
isSuccess,
isLoading,
isError,
} = useQuery({
queryKey,
queryFn: () => {
const item = safeLocalStorage.getItem(key)
if (!item) {
return initialValue
}
return JSON.parse(item) as T
},
})
const setValue: Dispatch<SetStateAction<T>> = useCallback(
(value) => {
const currentValue = queryClient.getQueryData<T>(queryKey) ?? initialValue
const valueToStore = value instanceof Function ? value(currentValue) : value
// Bail out when the value is unchanged (matches useState semantics).
// Without this, no-op updates from consumers — like a pruning effect
// whose updater returns `current` unchanged — still write to
// localStorage and invalidate the query, which churns subscribers and
// can cascade into "Maximum update depth exceeded" when two consumers
// of the same key are mounted together.
if (Object.is(valueToStore, currentValue)) return
safeLocalStorage.setItem(key, JSON.stringify(valueToStore))
queryClient.setQueryData(queryKey, valueToStore)
queryClient.invalidateQueries({ queryKey })
},
// initialValue is intentionally excluded: the function body reads the
// current value via queryClient.getQueryData so it doesn't close over
// initialValue reactively — including it would cause a new function
// reference every render when callers pass an inline literal (e.g. []).
// eslint-disable-next-line react-hooks/exhaustive-deps
[key, queryKey, queryClient]
)
return [storedValue, setValue, { isSuccess, isLoading, isError, error }] as const
}