| 1765 | * and wrapped response formats (when `select` is used). |
| 1766 | */ |
| 1767 | const updateCacheDataForKey = (key: QueryKey, items: Array<any>): void => { |
| 1768 | if (select) { |
| 1769 | // When `select` is used, the cache contains a wrapped response (e.g., { data: [...], meta: {...} }) |
| 1770 | // We need to update the cache while preserving the wrapper structure |
| 1771 | queryClient.setQueryData(key, (oldData: any) => { |
| 1772 | if (!oldData || typeof oldData !== `object`) { |
| 1773 | // No existing cache or not an object - don't corrupt the cache |
| 1774 | return oldData |
| 1775 | } |
| 1776 | |
| 1777 | if (Array.isArray(oldData)) { |
| 1778 | // Cache is already a raw array (shouldn't happen with select, but handle it) |
| 1779 | return items |
| 1780 | } |
| 1781 | |
| 1782 | // Use the select function to identify which property contains the items array. |
| 1783 | // This is more robust than guessing based on property order. |
| 1784 | const selectedArray = select(oldData) |
| 1785 | |
| 1786 | if (Array.isArray(selectedArray)) { |
| 1787 | // Find the property that matches the selected array by reference equality |
| 1788 | for (const propKey of Object.keys(oldData)) { |
| 1789 | if (oldData[propKey] === selectedArray) { |
| 1790 | // Found the exact property - create a shallow copy with updated items |
| 1791 | return { ...oldData, [propKey]: items } |
| 1792 | } |
| 1793 | } |
| 1794 | } |
| 1795 | |
| 1796 | // Fallback: check common property names used for data arrays |
| 1797 | if (Array.isArray(oldData.data)) { |
| 1798 | return { ...oldData, data: items } |
| 1799 | } |
| 1800 | if (Array.isArray(oldData.items)) { |
| 1801 | return { ...oldData, items: items } |
| 1802 | } |
| 1803 | if (Array.isArray(oldData.results)) { |
| 1804 | return { ...oldData, results: items } |
| 1805 | } |
| 1806 | |
| 1807 | // Last resort: find first array property |
| 1808 | for (const propKey of Object.keys(oldData)) { |
| 1809 | if (Array.isArray(oldData[propKey])) { |
| 1810 | return { ...oldData, [propKey]: items } |
| 1811 | } |
| 1812 | } |
| 1813 | |
| 1814 | // Couldn't safely identify the array property - don't corrupt the cache |
| 1815 | // Return oldData unchanged to avoid breaking select |
| 1816 | return oldData |
| 1817 | }) |
| 1818 | } else { |
| 1819 | // No select - cache contains raw array, just set it directly |
| 1820 | queryClient.setQueryData(key, items) |
| 1821 | } |
| 1822 | } |
| 1823 | |
| 1824 | /** |