@/store#createStore TypeScript Examples

The following examples show how to use @/store#createStore. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: store.ts    From atlas with GNU General Public License v3.0 6 votes vote down vote up
useAssetStore = createStore<AssetStoreState, AssetStoreActions>({
  state: {
    assets: {},
    pendingAssets: {},
    assetIdsBeingResolved: new Set(),
  },
  actionsFactory: (set) => ({
    addAsset: (contentId, asset) => {
      set((state) => {
        state.assets[contentId] = asset
      })
    },
    addPendingAsset: (contentId, storageDataObject) => {
      set((state) => {
        if (state.pendingAssets[contentId]) return
        state.pendingAssets[contentId] = storageDataObject
      })
    },
    removePendingAsset: (contentId) => {
      set((state) => {
        delete state.pendingAssets[contentId]
      })
    },
    addAssetBeingResolved: (contentId) => {
      set((state) => {
        state.assetIdsBeingResolved.add(contentId)
      })
    },
    removeAssetBeingResolved: (contentId) => {
      set((state) => {
        state.assetIdsBeingResolved.delete(contentId)
      })
    },
  }),
})
Example #2
Source File: bottomNav.ts    From atlas with GNU General Public License v3.0 6 votes vote down vote up
useBottomNavStore = createStore<BottomNavState, BottomNavActions>({
  state: INITIAL_STATE,
  actionsFactory: (set) => ({
    setOpen: (open) => {
      set((state) => {
        state.open = open
      })
    },
  }),
})
Example #3
Source File: connectionStatus.tsx    From atlas with GNU General Public License v3.0 6 votes vote down vote up
useConnectionStatusStore = createStore<ConnectionStatusStoreState, ConnectionStatusStoreActions>({
  state: { internetConnectionStatus: 'connected', nodeConnectionStatus: 'connecting' },
  actionsFactory: (set) => ({
    setNodeConnection: (connection) => {
      set((state) => {
        state.nodeConnectionStatus = connection
      })
    },
    setInternetConnection: (connection) => {
      set((state) => {
        state.internetConnectionStatus = connection
      })
    },
  }),
})
Example #4
Source File: store.ts    From atlas with GNU General Public License v3.0 6 votes vote down vote up
useEnvironmentStore = createStore<EnvironmentState, EnvironmentStoreActions>(
  {
    state: INITIAL_STATE,
    actionsFactory: (set) => ({
      setNodeOverride: (node) => {
        set((state) => {
          state.nodeOverride = node
        })
      },
      setTargetDevEnv: (env) => {
        set((state) => {
          state.targetDevEnv = env
        })
      },
    }),
  },
  {
    persist: {
      key: LOCAL_STORAGE_KEY,
      version: 0,
      whitelist: ['nodeOverride', 'targetDevEnv'],
      migrate: () => null,
    },
  }
)
Example #5
Source File: store.ts    From atlas with GNU General Public License v3.0 6 votes vote down vote up
useSearchStore = createStore<SearchState, SearchStoreActions>({
  state: INITIAL_STATE,
  actionsFactory: (set) => ({
    setSearchOpen: (open) => {
      set((state) => {
        state.searchOpen = open
      })
    },
    setSearchQuery: (query) => {
      set((state) => {
        state.searchQuery = query
      })
    },
  }),
})
Example #6
Source File: store.ts    From atlas with GNU General Public License v3.0 6 votes vote down vote up
useTransactionManagerStore = createStore<TransactionManagerStoreState, TransactionManagerStoreActions>({
  state: { blockActions: [], dialogStep: null, showFirstMintDialog: false, errorCode: null },
  actionsFactory: (set) => ({
    addBlockAction: (action) =>
      set((state) => {
        state.blockActions.push(action)
      }),
    removeOldBlockActions: (currentBlock) =>
      set((state) => {
        state.blockActions = state.blockActions.filter((action) => action.targetBlock > currentBlock)
      }),
    setDialogStep: (step) =>
      set((state) => {
        state.dialogStep = step
      }),
    setShowFistMintDialog: (show) =>
      set((state) => {
        state.showFirstMintDialog = show
      }),
    setErrorCode: (errorCode) =>
      set((state) => {
        state.errorCode = errorCode
      }),
  }),
})
Example #7
Source File: store.ts    From atlas with GNU General Public License v3.0 6 votes vote down vote up
useActiveUserStore = createStore<ActiveUserState, ActiveUserStoreActions>(
  {
    state: EMPTY_STATE,
    actionsFactory: (set) => ({
      resetActiveUser: () => {
        set((state) => ({ ...state, ...EMPTY_STATE }))
      },
      setActiveUser: (activeUserChanges) => {
        set((state) => {
          state.accountId = activeUserChanges.accountId !== undefined ? activeUserChanges.accountId : state.accountId
          state.memberId = activeUserChanges.memberId !== undefined ? activeUserChanges.memberId : state.memberId
          state.channelId = activeUserChanges.channelId !== undefined ? activeUserChanges.channelId : state.channelId
        })
      },
    }),
  },
  {
    persist: {
      key: LOCAL_STORAGE_KEY,
      version: 0,
      whitelist: WHITELIST,
      migrate: (oldState, oldVersion) => {
        // migrate store before zustand was added
        if (oldVersion === undefined) {
          const activeUser = readFromLocalStorage<ActiveUserState>(LOCAL_STORAGE_KEY)
          return activeUser
        }
      },
    },
  }
)
Example #8
Source File: drafts.ts    From atlas with GNU General Public License v3.0 5 votes vote down vote up
useDraftStore = createStore<DraftStoreState, DraftStoreActions>(
  {
    state: {
      drafts: [], // includes drafts for different channels
    },
    actionsFactory: (set) => ({
      addDraft: (draft, explicitId) => {
        const id = explicitId ?? createId()
        const updatedAt = new Date().toISOString()
        const newDraft: Draft = { ...draft, updatedAt, id, seen: false }
        set((draftState) => {
          draftState.drafts.unshift(newDraft)
        })
        return newDraft
      },
      updateDraft: (draftId, draftProps) => {
        const updatedAt = new Date().toISOString()
        set((draftState) => {
          const idx = draftState.drafts.findIndex((d) => d.id === draftId)
          if (idx >= 0) {
            draftState.drafts[idx] = { ...draftState.drafts[idx], ...draftProps, updatedAt }
          }
        })
      },
      removeDrafts: (draftIds) => {
        set((draftState) => {
          draftState.drafts = draftState.drafts.filter((draft) => !draftIds.includes(draft.id))
        })
      },
      removeAllDrafts: (channelId) => {
        set((draftState) => {
          draftState.drafts = draftState.drafts.filter((draft) => draft.channelId !== channelId)
        })
      },
      markAllDraftsAsSeenForChannel: (channelId) => {
        set((draftState) => {
          draftState.drafts = draftState.drafts.map((draft) => ({
            ...draft,
            seen: draft.channelId === channelId ? true : draft.seen,
          }))
        })
      },
    }),
  },
  {
    persist: {
      key: 'drafts',
      whitelist: ['drafts'],
      version: 1,
      migrate: (oldState, oldVersion, storageValue) => {
        // migrate store before zustand was added
        if (oldVersion === undefined) {
          const unseenDrafts = readFromLocalStorage<
            Array<{
              draftId: string
              channelId: string
            }>
          >('unseenDrafts')
          const drafts = [...(storageValue as Array<Draft>)].map((draft) => {
            return unseenDrafts?.find((unseen) => unseen.draftId === draft.id)
              ? { ...draft, seen: false }
              : { ...draft, seen: true }
          })
          return {
            drafts: drafts,
          }
        }
      },
    },
  }
)
Example #9
Source File: notifications.store.ts    From atlas with GNU General Public License v3.0 5 votes vote down vote up
useNotificationStore = createStore<NotificationsStoreState, NotificationsStoreActions>(
  {
    state: {
      lastSeenNotificationBlock: 0,
      readNotificationsIdsMap: {},
    },
    actionsFactory: (set) => ({
      markNotificationsAsRead: (ids) => {
        const _ids = Array.isArray(ids) ? ids : [ids]

        set((state) => {
          _ids.forEach(({ id }) => {
            state.readNotificationsIdsMap[id] = true
          })
        })
      },
      markNotificationsAsUnread: (ids) => {
        const _ids = Array.isArray(ids) ? ids : [ids]

        set((state) => {
          _ids.forEach(({ id }) => {
            state.readNotificationsIdsMap[id] = false
          })
        })
      },
      setLastSeenNotificationBlock: (block) => {
        set((state) => {
          state.lastSeenNotificationBlock = block
        })
      },
    }),
  },
  {
    persist: {
      key: 'notifications',
      whitelist: ['lastSeenNotificationBlock', 'readNotificationsIdsMap'],
      version: 0,
      migrate: (state) => {
        return {
          ...state,
        }
      },
    },
  }
)
Example #10
Source File: store.ts    From atlas with GNU General Public License v3.0 5 votes vote down vote up
useSnackbarStore = createStore<SnackbarStoreState, SnackbarStoreActions>({
  state: {
    snackbars: [],
  },
  actionsFactory: (set, get) => ({
    updateSnackbar: (id, opts) => {
      set((state) => {
        const snackbarIdx = state.snackbars.findIndex((s) => s.id === id)
        if (snackbarIdx === -1) return
        state.snackbars[snackbarIdx] = { ...state.snackbars[snackbarIdx], ...opts }
      })
    },
    closeSnackbar: (id) =>
      set((state) => {
        state.snackbars = state.snackbars.filter((snackbar) => snackbar.id !== id)
      }),

    displaySnackbar: ({ timeout, customId, onExit, ...args }) => {
      const id = customId ?? createId()
      set((state) => {
        state.snackbars.push({ id, timeout, ...args })
      })
      if (timeout) {
        onExit?.()
        const timeoutId = window.setTimeout(() => {
          set((state) => {
            state.snackbars = state.snackbars.filter((snackbar) => snackbar.id !== id)
          })
        }, timeout)
        set((state) => {
          const snackbarIdx = state.snackbars.findIndex((snackbar) => snackbar.id === id)
          state.snackbars[snackbarIdx].timeoutId = timeoutId
        })
      }
      return id
    },
    cancelSnackbarTimeout: (id) => {
      const snackbar = get().snackbars.find((snackbar) => snackbar.id === id)
      window.clearTimeout(snackbar?.timeoutId)
    },
    restartSnackbarTimeout: (id) => {
      const snackbar = get().snackbars.find((snackbar) => snackbar.id === id)
      if (snackbar?.timeout) {
        window.setTimeout(() => {
          set((state) => {
            state.snackbars = state.snackbars.filter((snackbar) => snackbar.id !== id)
          })
        }, snackbar.timeout)
      }
    },
  }),
})
Example #11
Source File: store.ts    From atlas with GNU General Public License v3.0 5 votes vote down vote up
useUploadsStore = createStore<UploadStoreState, UploadStoreActions>(
  {
    actionsFactory: (set) => ({
      setUploadStatus: (contentId, status) => {
        set((state) => {
          state.uploadsStatus[contentId] = { ...state.uploadsStatus[contentId], ...status }
        })
      },
      addAssetFile: (assetFile) => {
        set((state) => {
          state.assetsFiles.push(assetFile)
        })
      },
      addAssetToUploads: (asset) => {
        set((state) => {
          state.uploads.push(asset)
        })
      },
      removeAssetFromUploads: (contentId) => {
        set((state) => {
          state.uploads = state.uploads.filter((asset) => asset.id !== contentId)
        })
      },
      removeAssetsWithParentFromUploads: (type, id) => {
        set((state) => {
          state.uploads = state.uploads.filter(
            (asset) => asset.parentObject.id !== id || asset.parentObject.type !== type
          )
        })
      },
      setIsSyncing: (isSyncing) => {
        set((state) => {
          state.isSyncing = isSyncing
        })
      },
      addProcessingAsset: (contentId) => {
        set((state) => {
          state.processingAssets.push({ id: contentId, expiresAt: Date.now() + UPLOAD_PROCESSING_TIMEOUT })
        })
      },
      removeProcessingAsset: (contentId) => {
        set((state) => {
          state.processingAssets = state.processingAssets.filter((processingAsset) => processingAsset.id !== contentId)
        })
      },
      addNewChannelId: (channelId) => {
        set((state) => {
          state.newChannelsIds.push(channelId)
        })
      },
    }),
    state: {
      uploads: [],
      uploadsStatus: {},
      assetsFiles: [],
      isSyncing: false,
      processingAssets: [],
      newChannelsIds: [],
    },
  },
  {
    persist: {
      key: UPLOADS_LOCAL_STORAGE_KEY,
      whitelist: ['uploads', 'processingAssets'],
      version: 0,
      migrate: (state) => {
        const uploads = window.localStorage.getItem(UPLOADS_LOCAL_STORAGE_KEY)
        return {
          ...state,
          uploads: JSON.parse(uploads || ''),
        }
      },
    },
  }
)
Example #12
Source File: store.ts    From atlas with GNU General Public License v3.0 4 votes vote down vote up
usePersonalDataStore = createStore<PersonalDataStoreState, PersonalDataStoreActions>(
  {
    state: initialState,
    actionsFactory: (set) => ({
      updateWatchedVideos: (__typename, id, timestamp) => {
        set((state) => {
          const currentVideo = state.watchedVideos.find((v) => v.id === id)
          if (!currentVideo) {
            const newVideo = __typename === 'COMPLETED' ? { __typename, id } : { __typename, id, timestamp }
            state.watchedVideos.push(newVideo)
          } else {
            const index = state.watchedVideos.findIndex((v) => v.id === id)
            if (index !== -1) state.watchedVideos[index] = { __typename, id, timestamp }
          }
        })
      },
      updateChannelFollowing: (id, follow) => {
        set((state) => {
          const isFollowing = state.followedChannels.some((channel) => channel.id === id)
          if (isFollowing && !follow) {
            state.followedChannels = state.followedChannels.filter((channel) => channel.id !== id)
          }
          if (!isFollowing && follow) {
            state.followedChannels.push({ id })
          }
        })
      },
      addRecentSearch: (title) => {
        set((state) => {
          const filteredCurrentSearches = state.recentSearches.filter((item) => item.title !== title)
          const newSearches = [{ title }, ...filteredCurrentSearches]
          state.recentSearches = newSearches.slice(0, 6)
        })
      },
      deleteRecentSearch: (title) => {
        set((state) => {
          state.recentSearches = state.recentSearches.filter((search) => search.title !== title)
        })
      },
      updateDismissedMessages: (id, add = true) => {
        set((state) => {
          state.dismissedMessages = state.dismissedMessages.filter((dissmissedMessage) => dissmissedMessage.id !== id)
          if (add) {
            state.dismissedMessages.unshift({ id })
          }
        })
      },
      setCurrentVolume: (volume) =>
        set((state) => {
          state.currentVolume = round(volume, 2)
        }),
      setCachedVolume: (volume) =>
        set((state) => {
          state.cachedVolume = round(volume, 2)
        }),
      setCinematicView: (cinematicView) =>
        set((state) => {
          state.cinematicView = cinematicView
        }),
      setCookiesAccepted: (accept) =>
        set((state) => {
          state.cookiesAccepted = accept
        }),
    }),
  },
  {
    persist: {
      key: 'personalData',
      whitelist: WHITELIST,
      version: 2,
      migrate: (oldState) => {
        const typedOldState = oldState as PersonalDataStoreState

        const migratedWatchedVideos = typedOldState.watchedVideos.reduce((acc, cur) => {
          const migratedId = (videoIdsMapEntries as Record<string, string>)[cur.id]
          if (migratedId) {
            return [...acc, { ...cur, id: migratedId }]
          }
          return acc
        }, [] as WatchedVideo[])

        const migratedFollowedChannels = typedOldState.followedChannels.reduce((acc, cur) => {
          const migratedId = (channelIdsMapEntries as Record<string, string>)[cur.id]
          if (migratedId) {
            return [...acc, { ...cur, id: migratedId }]
          }
          return acc
        }, [] as FollowedChannel[])

        const migratedState: PersonalDataStoreState = {
          ...typedOldState,
          watchedVideos: migratedWatchedVideos,
          followedChannels: migratedFollowedChannels,
        }
        return migratedState
      },
    },
  }
)