Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion packages/common/src/api/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ export * from './tan-query/tracks/useRemixedTracks'

// Users
export * from './tan-query/users/account/useCurrentUserId'
export * from './tan-query/users/account/useCurrentUser'
export * from './tan-query/users/account/useWalletUser'
export * from './tan-query/users/account/useAddToPlaylistFolder'
export * from './tan-query/users/account/useCurrentAccount'
export * from './tan-query/users/account/usePlaylistLibrary'
Expand Down
2 changes: 2 additions & 0 deletions packages/common/src/api/tan-query/queryKeys.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
export const QUERY_KEYS = {
aiTracks: 'aiTracks',
accountUser: 'accountUser',
walletUser: 'walletUser',
walletAccount: 'walletAccount',
trackCommentList: 'trackCommentList',
userCommentList: 'userCommentList',
comment: 'comment',
Expand Down
10 changes: 1 addition & 9 deletions packages/common/src/api/tan-query/tracks/useDeleteTrack.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Id } from '@audius/sdk'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { useDispatch, useSelector } from 'react-redux'
import { useDispatch } from 'react-redux'

import { useAudiusQueryContext } from '~/audius-query'
import { useAppContext } from '~/context/appContext'
Expand All @@ -9,10 +9,8 @@ import { Feature } from '~/models/ErrorReporting'
import { ID } from '~/models/Identifiers'
import { Track } from '~/models/Track'
import { UserMetadata } from '~/models/User'
import { getWalletAddresses } from '~/store/account/selectors'
import { deleteTrackRequested } from '~/store/cache/tracks/actions'

import { getCurrentUserQueryKey } from '../users/account/useCurrentUser'
import { useCurrentUserId } from '../users/account/useCurrentUserId'
import { useUser } from '../users/useUser'
import { primeTrackData } from '../utils/primeTrackData'
Expand All @@ -35,7 +33,6 @@ export const useDeleteTrack = () => {
const queryClient = useQueryClient()
const dispatch = useDispatch()
const { data: currentUserId } = useCurrentUserId()
const { currentUser: currentUserWallet } = useSelector(getWalletAddresses)
const { data: currentUser } = useUser(currentUserId)
const {
analytics: { track: trackEvent }
Expand Down Expand Up @@ -78,11 +75,6 @@ export const useDeleteTrack = () => {
dispatch,
forceReplace: true
})

queryClient.setQueryData(
getCurrentUserQueryKey(currentUserWallet),
updatedCurrentUser
)
}

// Optimistic update in cache
Expand Down
48 changes: 0 additions & 48 deletions packages/common/src/api/tan-query/users/account/useCurrentUser.ts

This file was deleted.

59 changes: 59 additions & 0 deletions packages/common/src/api/tan-query/users/account/useWalletUser.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import { AudiusSdk } from '@audius/sdk'
import { useQuery } from '@tanstack/react-query'
import { useSelector } from 'react-redux'

import { accountFromSDK } from '~/adapters/user'
import { useAudiusQueryContext } from '~/audius-query'
import { AccountUserMetadata, ID } from '~/models'
import { getWalletAddresses } from '~/store/account/selectors'

import { QUERY_KEYS } from '../../queryKeys'
import { QueryKey, SelectableQueryOptions } from '../../types'

export const getWalletAccountQueryKey = (wallet: string | null | undefined) =>
[
QUERY_KEYS.walletAccount,
wallet
] as unknown as QueryKey<AccountUserMetadata | null>

export const getWalletUserQueryKey = (wallet: string | null | undefined) =>
[QUERY_KEYS.walletUser, wallet] as unknown as QueryKey<ID | null>

// This queryFn is separate in order to be used in sagas
export const getWalletAccountQueryFn = async (
wallet: string,
sdk: AudiusSdk
) => {
const { data } = await sdk.full.users.getUserAccount({
wallet
})

if (!data) {
console.warn('Missing user from account response')
return null
}

const account = accountFromSDK(data)
return account
}

/**
* Hook to get the currently logged in user's data
*/
export const useWalletUser = <TResult = ID | null | undefined>(
options?: SelectableQueryOptions<ID | null | undefined, TResult>
) => {
const { audiusSdk } = useAudiusQueryContext()
const { currentUser: currentUserWallet } = useSelector(getWalletAddresses)

return useQuery({
queryKey: getWalletUserQueryKey(currentUserWallet),
queryFn: async () => {
const sdk = await audiusSdk()
return (await getWalletAccountQueryFn(currentUserWallet!, sdk))?.user
?.user_id
},
...options,
enabled: options?.enabled !== false && !!currentUserWallet
})
}
8 changes: 4 additions & 4 deletions packages/common/src/api/tan-query/users/useUpdateUser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { ID } from '~/models/Identifiers'
import { PlaylistLibrary } from '~/models/PlaylistLibrary'
import { UserMetadata } from '~/models/User'

import { getCurrentUserQueryKey } from './account/useCurrentUser'
import { getCurrentAccountQueryKey } from './account/useCurrentAccount'
import { getUserQueryKey } from './useUser'

type MutationContext = {
Expand Down Expand Up @@ -53,7 +53,7 @@ export const useUpdateUser = () => {
// Snapshot the previous account user if it matches
const previousAccountUser = queryClient
.getQueriesData<UserMetadata>({
queryKey: getCurrentUserQueryKey(userId.toString())
queryKey: getCurrentAccountQueryKey(userId)
})
.find(([_, data]) => data?.user_id === userId)?.[1]

Expand All @@ -65,7 +65,7 @@ export const useUpdateUser = () => {

// Optimistically update accountUser queries if they match the user
queryClient.setQueriesData(
{ queryKey: getCurrentUserQueryKey(userId.toString()) },
{ queryKey: getCurrentAccountQueryKey(userId) },
(oldData: any) => {
if (!oldData?.user_id || oldData.user_id !== userId) return oldData
return { ...oldData, ...metadata }
Expand All @@ -84,7 +84,7 @@ export const useUpdateUser = () => {
// Roll back accountUser queries if we have the previous state
if (context?.previousAccountUser) {
queryClient.setQueriesData(
{ queryKey: getCurrentUserQueryKey(userId.toString()) },
{ queryKey: getCurrentAccountQueryKey(userId) },
(oldData: any) => {
if (!oldData?.user_id || oldData.user_id !== userId) return oldData
return context.previousAccountUser
Expand Down
29 changes: 2 additions & 27 deletions packages/common/src/api/user.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
import { full, Id, OptionalId } from '@audius/sdk'

import { accountFromSDK, userMetadataListFromSDK } from '~/adapters/user'
import { userMetadataListFromSDK } from '~/adapters/user'
import { createApi } from '~/audius-query'
import { ID, Kind, StringUSDC } from '~/models'
import {
USDCTransactionDetails,
USDCTransactionMethod,
USDCTransactionType
} from '~/models/USDCTransactions'
import { isResponseError } from '~/utils'
import { Nullable } from '~/utils/typeUtils'

type GetUSDCTransactionListArgs = {
Expand Down Expand Up @@ -43,30 +42,7 @@ const parseTransaction = ({
const userApi = createApi({
reducerPath: 'userApi',
endpoints: {
// TODO: Remove this once saga calls are removed
getUserAccount: {
fetch: async ({ wallet }: { wallet: string }, { audiusSdk }) => {
try {
const sdk = await audiusSdk()
const { data } = await sdk.full.users.getUserAccount({ wallet })
if (!data) {
console.warn('Missing user from account response')
return null
}

return accountFromSDK(data)
} catch (e) {
// Account doesn't exist, don't bubble up an error, just return null
if (isResponseError(e) && [401, 404].includes(e.response.status)) {
return null
}
throw e
}
},
options: {
schemaKey: 'accountUser'
}
},
// TODO: Remove these once fetch export calls are removed
getUserByHandle: {
fetch: async (
{
Expand Down Expand Up @@ -135,6 +111,5 @@ const userApi = createApi({

export const userApiReducer = userApi.reducer
export const userApiFetch = userApi.fetch
export const userApiFetchSaga = userApi.fetchSaga
export const userApiActions = userApi.actions
export const userApiUtils = userApi.util
26 changes: 14 additions & 12 deletions packages/common/src/store/account/sagas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import {
takeLatest
} from 'typed-redux-saga'

import { userApiFetchSaga } from '~/api/user'
import { getWalletAccountQueryFn, getWalletAccountQueryKey } from '~/api'
import { AccountUserMetadata, ErrorLevel, Kind, UserMetadata } from '~/models'
import { getContext } from '~/store/effects'
import { chatActions } from '~/store/pages/chat'
Expand Down Expand Up @@ -103,15 +103,18 @@ function* initializeMetricsForUser({
const solanaWalletService = yield* getContext('solanaWalletService')
const analytics = yield* getContext('analytics')
const sdk = yield* getSDK()
const queryClient = yield* getContext('queryClient')

if (accountUser && accountUser.handle) {
const [web3WalletAddress] = yield* call([
sdk.services.audiusWalletClient,
sdk.services.audiusWalletClient.getAddresses
])
const { user: web3User } = yield* call(userApiFetchSaga.getUserAccount, {
wallet: web3WalletAddress
})
const accountData = (yield* call([queryClient, queryClient.fetchQuery], {
queryKey: getWalletAccountQueryKey(web3WalletAddress),
queryFn: async () => getWalletAccountQueryFn(web3WalletAddress, sdk)
})) as AccountUserMetadata | undefined
const { user: web3User } = accountData ?? {}

let solanaWallet
let managerUserId
Expand Down Expand Up @@ -164,13 +167,15 @@ export function* fetchAccountAsync({
const localStorage = yield* getContext('localStorage')
const reportToSentry = yield* getContext('reportToSentry')
const sdk = yield* getSDK()
const queryClient = yield* getContext('queryClient')

// Don't revert successful local account fetch
if (shouldMarkAccountAsLoading) {
yield* put(fetchAccountRequested())
}

let wallet, web3WalletAddress
let wallet: string | undefined
let web3WalletAddress: string | undefined
try {
const connectedWallets = yield* call([
sdk.services.audiusWalletClient,
Expand Down Expand Up @@ -200,13 +205,10 @@ export function* fetchAccountAsync({
return
}

const accountData: AccountUserMetadata | undefined = yield* call(
userApiFetchSaga.getUserAccount,
{
wallet
},
true // force refresh to get updated user w handle
)
const accountData = (yield* call([queryClient, queryClient.fetchQuery], {
queryKey: getWalletAccountQueryKey(wallet),
queryFn: async () => getWalletAccountQueryFn(wallet!, sdk)
})) as AccountUserMetadata | undefined

if (!accountData) {
yield* put(resetAccount())
Expand Down
28 changes: 17 additions & 11 deletions packages/web/src/common/store/pages/signon/sagas.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
import { userApiFetchSaga } from '@audius/common/api'
import {
getWalletAccountQueryFn,
getWalletAccountQueryKey
} from '@audius/common/api'
import { GUEST_EMAIL } from '@audius/common/hooks'
import {
Name,
Expand Down Expand Up @@ -538,6 +541,7 @@ function* createGuestAccount(
function* signUp() {
const reportToSentry = yield* getContext('reportToSentry')
const localStorage = yield* getContext('localStorage')
const queryClient = yield* getContext('queryClient')

try {
const signOn = yield* select(getSignOn)
Expand Down Expand Up @@ -587,12 +591,14 @@ function* signUp() {
sdk.services.audiusWalletClient,
sdk.services.audiusWalletClient.getAddresses
])
const account: AccountUserMetadata | null = yield* call(
userApiFetchSaga.getUserAccount,
const account = (yield* call(
[queryClient, queryClient.fetchQuery],
{
wallet
queryKey: getWalletAccountQueryKey(wallet),
queryFn: async () => getWalletAccountQueryFn(wallet!, sdk)
}
)
)) as AccountUserMetadata | undefined
// TODO: Do I need to prime the accountUser slice here?
if (!account) {
throw new Error('Account user ID does not exist')
}
Expand Down Expand Up @@ -858,6 +864,7 @@ function* signIn(action: ReturnType<typeof signOnActions.signIn>) {
const authService = yield* getContext('authService')
const isNativeMobile = yield* getContext('isNativeMobile')
const isElectron = yield* getContext('isElectron')
const queryClient = yield* getContext('queryClient')
const clientOrigin = isNativeMobile
? 'mobile'
: isElectron
Expand Down Expand Up @@ -896,12 +903,11 @@ function* signIn(action: ReturnType<typeof signOnActions.signIn>) {
return
}

const account: AccountUserMetadata | null = yield* call(
userApiFetchSaga.getUserAccount,
{
wallet: signInResponse.walletAddress
}
)
const account = (yield* call([queryClient, queryClient.fetchQuery], {
queryKey: getWalletAccountQueryKey(signInResponse.walletAddress),
queryFn: async () =>
getWalletAccountQueryFn(signInResponse.walletAddress, sdk)
})) as AccountUserMetadata | undefined

// Login succeeded but we found no account for the user (incomplete signup)
if (!account) {
Expand Down
Loading