How to set pre selected ids initially in a IndexTable in Polaris component
I have tried using react state which works fine but when I select any other row then the initially set all the records gets deselected. Could anyone please help?
export default function Index() {
// data coming from loader function
const { session, dropshipperId, merchantCount, merchant, pagination } = useLoaderData < typeof loader > ()
const navigate = useNavigate()
// selection of merchants
const { selectedResources, allResourcesSelected, handleSelectionChange } = useIndexResourceState(merchant);
// loading state of save merchants table
const [addRemoveLoading, setAddRemoveLoading] = useState < boolean > (false)
// array to store selected merchants id
const [selectedMerchantIds, setSelectedMerchantIds] = useState < string[] > ([])
const [allMerchantsSelected, setAllMerchantsSelected] = useState < boolean > (false)
// toast message to show once saved
const [showToast, setShowToast] = useState < boolean > (false)
// useEffect to get previously stored merchant ids subscribed by dropshipper
useEffect(() => {
const initialMerchantIds = async () => {
/* Get merchant ids subscribed by dropshipper */
try {
const merchantIdsDataResponse = await fetch(`http://localhost:4000/get-merchant`, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({ dropshipperId })
})
if (merchantIdsDataResponse.ok) {
const merchantIdsDataJSON = await merchantIdsDataResponse.json()
setSelectedMerchantIds(merchantIdsDataJSON.data.merchants)
if (merchantIdsDataJSON.data.merchants) {
if (merchantIdsDataJSON.data.merchants.length == merchant.length) {
setAllMerchantsSelected(true)
}
}
} else {
throw new Error('Failed to fetch merchant data');
}
} catch (error) {
console.error('Error fetching merchant data:', error);
}
/* Get merchant ids subscribed by dropshipper */
}
initialMerchantIds()
}, [])
// on change selection of merchants update selected merchant ids
useEffect(() => {
setSelectedMerchantIds(prevSelectedIds => {
// return Array.from(new Set([...prevSelectedIds, ...selectedResources]));
return selectedResources
})
setAllMerchantsSelected(allResourcesSelected)
}, [selectedResources])
// merchant pagination
const pagi = useMemo(() => {
if (!pagination) {
// Handle case where paginationP is null or undefined
return null; // or some default value
}
const { current, pageSize, total } = pagination
return {
previous: {
disabled: current <= 1,
link: `/app/?page=${current - 1}&pageSize=${pageSize}`
},
next: {
disabled: current == Math.ceil(total / pageSize),
link: `/app/?page=${current + 1}&pageSize=${pageSize}`
}
}
}, [pagination])
// rows and columns of merchant table
const rowMarkup = merchant?.map(({ id, shop, name, url }: Merchant, index: number) => (
))
// resource name of merchant
const resourceNameMerchant = {
singular: 'merchant',
plural: 'merchants'
}
// empty state to display when no data present
const emptyStateMarkup = (type: string) => (