| 1 |
import { useEffect, useState } from '@wordpress/element' |
| 2 |
import create from 'zustand' |
| 3 |
import { devtools, persist } from 'zustand/middleware' |
| 4 |
import { getUserSelectionData, saveUserSelectionData } from '@assist/api/Data' |
| 5 |
|
| 6 |
const state = () => ({ |
| 7 |
siteType: {}, |
| 8 |
siteInformation: { |
| 9 |
title: undefined, |
| 10 |
}, |
| 11 |
feedbackMissingSiteType: '', |
| 12 |
feedbackMissingGoal: '', |
| 13 |
exitFeedback: undefined, |
| 14 |
siteTypeSearch: [], |
| 15 |
style: null, |
| 16 |
pages: [], |
| 17 |
plugins: [], |
| 18 |
goals: [], |
| 19 |
}) |
| 20 |
|
| 21 |
// This checks the local storage cache for the user selections set in Launch, if any |
| 22 |
const cachedSelections = localStorage.getItem('extendify-site-selection') |
| 23 |
const storage = { |
| 24 |
getItem: cachedSelections |
| 25 |
? () => { |
| 26 |
localStorage.removeItem('extendify-site-selection') |
| 27 |
return cachedSelections |
| 28 |
} |
| 29 |
: async () => JSON.stringify(await getUserSelectionData()), |
| 30 |
setItem: async (_, value) => await saveUserSelectionData(value), |
| 31 |
removeItem: () => undefined, |
| 32 |
} |
| 33 |
|
| 34 |
export const useSelectionStore = create( |
| 35 |
persist(devtools(state, { name: 'Extendify User Selections' }), { |
| 36 |
name: 'extendify-site-selection', |
| 37 |
getStorage: () => storage, |
| 38 |
}), |
| 39 |
state, |
| 40 |
) |
| 41 |
|
| 42 |
/* Hook useful for when you need to wait on the async state to hydrate */ |
| 43 |
export const useSelectionStoreReady = () => { |
| 44 |
const [hydrated, setHydrated] = useState( |
| 45 |
useSelectionStore.persist.hasHydrated, |
| 46 |
) |
| 47 |
useEffect(() => { |
| 48 |
const unsubFinishHydration = |
| 49 |
useSelectionStore.persist.onFinishHydration(() => setHydrated(true)) |
| 50 |
return () => { |
| 51 |
unsubFinishHydration() |
| 52 |
} |
| 53 |
}, []) |
| 54 |
return hydrated |
| 55 |
} |
| 56 |
|