Query Sanity documents by matching IDs from user's array
Looking at your code, you're currently fetching ALL pieces from Sanity, but you need to filter them based on the pieceID values stored in your user's closet array. You'll want to use the in operator in GROQ to check if a piece's pieceID exists in your array.
Here's how to modify your query:
// Assuming you have an array of pieceIDs from the user's closet
const userClosetIds = ['id1', 'id2', 'id3']; // Your array of pieceIDs
sanityClient
.fetch(`*[_type == "piece" && pieceID in $closetIds]{
title,
slug,
pieceID,
mainImage {
asset->{
_id,
url
},
alt
},
}`, { closetIds: userClosetIds })
.then((data) => setPieceData(data))
.catch(console.error);The key changes:
- Added the filter condition:
&& pieceID in $closetIdschecks if the piece'spieceIDexists in your array - Used a parameter:
$closetIdsis passed as a parameter for security and performance - Passed the parameter: The second argument to
.fetch()contains your array of IDs
The in operator in GROQ checks if a value exists in an array, which is exactly what you need here. This will only return pieces whose pieceID matches one of the IDs in your user's closet array.
If your array is empty, the query will return no results (which is the correct behavior for an empty closet). Make sure your pieceID field in your Sanity schema matches the format of the IDs you're storing in the user's closet array.
Show original thread7 replies
Sanity – Build the way you think, not the way your CMS thinks
Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.