| 1 |
import { safeParseJson } from '@shared/lib/parsing'; |
| 2 |
import apiFetch from '@wordpress/api-fetch'; |
| 3 |
import { create } from 'zustand'; |
| 4 |
import { createJSONStorage, devtools, persist } from 'zustand/middleware'; |
| 5 |
|
| 6 |
const startingState = { |
| 7 |
siteType: { |
| 8 |
slug: '0default', |
| 9 |
name: 'Default', |
| 10 |
}, |
| 11 |
siteInformation: { |
| 12 |
title: undefined, |
| 13 |
}, |
| 14 |
style: null, |
| 15 |
pages: [], |
| 16 |
sitePlugins: [], |
| 17 |
// initialize the state with default values |
| 18 |
...(safeParseJson(window.extSharedData.launchDataLegacy)?.state ?? {}), |
| 19 |
}; |
| 20 |
|
| 21 |
const state = () => ({ |
| 22 |
...startingState, |
| 23 |
// Add methods here |
| 24 |
}); |
| 25 |
|
| 26 |
const path = '/extendify/v1/shared/user-selections-data'; |
| 27 |
const storage = { |
| 28 |
getItem: async () => await apiFetch({ path }), |
| 29 |
setItem: async (_name, state) => |
| 30 |
await apiFetch({ path, method: 'POST', data: { state } }), |
| 31 |
}; |
| 32 |
|
| 33 |
export const useUserSelectionStore = create( |
| 34 |
persist(devtools(state, { name: 'Extendify User Selections' }), { |
| 35 |
storage: createJSONStorage(() => storage), |
| 36 |
skipHydration: true, |
| 37 |
}), |
| 38 |
state, |
| 39 |
); |
| 40 |
|