Fetching data without Sanity client using queries and filters.

4 replies
Last updated: Jun 15, 2022
Hi guys. How would I fetch data without sanity client with queries and filter? I know that this works const query = `*[_type=="tweet"]`; const url = `https://<projectId>.
api.sanity.io/v1/data/query/development?query=${query} `; const tweets = await fetch(url).then(res => res.json());

but how would I use this query with filtering
const currentUserTweetsQuery =
*[_type == "tweet" && userId == '${userId}] | order(_createdAt desc)
? (this works via sanity online and via sanity client fetch)into const url = `https://<projectId>.
api.sanity.io/v1/data/query/development?query=${currentUserTweetsQuery} `;const tweets = await fetch(url).then(res => res.json());

Thanks in advance for the help! New to sanity.
Jun 15, 2022, 6:03 AM
You’d use a parameter in your query instead of inlining a value. And then you’d pass that parameter as a URL parameter.
Jun 15, 2022, 7:43 AM
const query = `*[ _type == "tweet" && userId == $userId ]`
const url = `https://…?query=${query}&userId=${userId}`
Jun 15, 2022, 7:44 AM
Don‘t forget to run both the query and every paremeter through
encodeURIComponent
(individually).
Jun 15, 2022, 7:45 AM
I figured it out before but thanks for your reply! I tried what you suggested It didn't, just seeing how many ways it can be done. Yea I got it to work and did wrap my initial query in there and it worked, the query via client and online sanity. For those who are reading, this worked for me, to get the latest data because for some reason sanityClient.fetch doesn't give me the latest data after closing the tab, and coming back fresh data is not there even though it's in the database, in nextjs, unless you reload page.
const baseUrl =
https://${process.env.NEXT_PUBLIC_SANITY_PROJECT_ID}.<http://api.sanity.io/v2022-05-10/data/query/development?query=|api.sanity.io/v2022-05-10/data/query/development?query=>

const userTweetsQuery = encodeURIComponent(
*[_type == "tweet" && userId == '${userId}'] | order(_createdAt desc)
);
fetch(
${baseUrl}${userTweetsQuery}
) .then(res =&gt; res.json())
.then(userTweets =&gt; {
console.log(userTweets)
})
.catch(error =&gt; {console.log(error.message)})
Jun 15, 2022, 9:25 AM

Sanity– build remarkable experiences at scale

Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Was this answer helpful?