T
TanStack17mo ago
conscious-sapphire

Hash sets correcly

JSON.stringify doesn't work correcly with sets. i have an object with filters that are sets and i pass these into the query function, whenever the set changes it doesn't change the queryKey correctly
const filters = ref({
status: new Set()
})

const { data: response, isLoading } = useQuery({
queryKey: ['orders', 'collection', filters],
queryFn: async ({ signal }) => ordersService.get({ filters: filters.value, signal }),
placeholderData: keepPreviousData
})

filters.value.source.add('created')

const query = computed(() => {
return ['orders', 'collection', filters] // this changes correctly
})
const hash = computed(() => {
return JSON.stringify(query.value) // here status stays `"status": {}` whatever is inside
})
const filters = ref({
status: new Set()
})

const { data: response, isLoading } = useQuery({
queryKey: ['orders', 'collection', filters],
queryFn: async ({ signal }) => ordersService.get({ filters: filters.value, signal }),
placeholderData: keepPreviousData
})

filters.value.source.add('created')

const query = computed(() => {
return ['orders', 'collection', filters] // this changes correctly
})
const hash = computed(() => {
return JSON.stringify(query.value) // here status stays `"status": {}` whatever is inside
})
Is there something we can do to let this work? i tried
queryKey: ['orders', 'collection', filters, { status: [...filters.value.status] }],
queryKey: ['orders', 'collection', filters, { status: [...filters.value.status] }],
but no luck, i really wish to keep using sets
2 Replies
conscious-sapphire
conscious-sapphireOP17mo ago
for now this fixed it for me
export class SerializableSet extends Set {
toJSON() {
return Array.from(this);
}
}

const filters = ref({
status: new SerializableSet()
})
export class SerializableSet extends Set {
toJSON() {
return Array.from(this);
}
}

const filters = ref({
status: new SerializableSet()
})

Did you find this page helpful?