fix(plugin-multi-tenant): incorrect tenant selection with postgres (#10992)

### What
1. List view not working when clearing tenant selection (you would see a
NaN error)
2. Tenant selector would reset to the first option when loading a
document

### Why
1. Using parseFloat on the _ALL_ selection option
2. A was mismatch in ID types was causing the selector to never find a
matching option, thus resetting it to the first option

### How
1. Check if cookie isNumber before parsing
2. Do not cast select option values to string anymore

Fixes https://github.com/payloadcms/payload/issues/9821
Fixes https://github.com/payloadcms/payload/issues/10980
This commit is contained in:
Jarrod Flesch
2025-02-05 09:56:27 -05:00
committed by GitHub
parent 8af8befbd4
commit 2a1ddf1e89
3 changed files with 17 additions and 10 deletions

View File

@@ -42,7 +42,7 @@ export const TenantSelector = ({ viewType }: { viewType?: ViewTypes }) => {
selectedTenantID
? selectedTenantID === SELECT_ALL
? undefined
: String(selectedTenantID)
: (selectedTenantID as string)
: undefined
}
/>

View File

@@ -33,7 +33,7 @@ export const TenantSelectionProvider = async ({
})
tenantOptions = docs.map((doc) => ({
label: String(doc[useAsTitle]),
value: String(doc.id),
value: doc.id,
}))
} catch (_) {
// user likely does not have access
@@ -42,15 +42,17 @@ export const TenantSelectionProvider = async ({
const cookies = await getCookies()
let tenantCookie = cookies.get('payload-tenant')?.value
let initialValue = undefined
const isValidTenantCookie =
(tenantOptions.length > 1 && tenantCookie === SELECT_ALL) ||
tenantOptions.some((option) => option.value === tenantCookie)
if (isValidTenantCookie) {
initialValue = tenantCookie
if (tenantOptions.length > 1 && tenantCookie === SELECT_ALL) {
initialValue = SELECT_ALL
} else {
tenantCookie = undefined
initialValue = tenantOptions.length > 1 ? SELECT_ALL : tenantOptions[0]?.value
const matchingOption = tenantOptions.find((option) => String(option.value) === tenantCookie)
if (matchingOption) {
initialValue = matchingOption.value
} else {
tenantCookie = undefined
initialValue = tenantOptions.length > 1 ? SELECT_ALL : tenantOptions[0]?.value
}
}
return (

View File

@@ -1,4 +1,5 @@
import { parseCookies } from 'payload'
import { isNumber } from 'payload/shared'
/**
* A function that takes request headers and an idType and returns the current tenant ID from the cookie
@@ -13,5 +14,9 @@ export function getTenantFromCookie(
): null | number | string {
const cookies = parseCookies(headers)
const selectedTenant = cookies.get('payload-tenant') || null
return selectedTenant ? (idType === 'number' ? parseFloat(selectedTenant) : selectedTenant) : null
return selectedTenant
? idType === 'number' && isNumber(selectedTenant)
? parseFloat(selectedTenant)
: selectedTenant
: null
}