👀 Our most exciting product launch yet 🚀 Join us May 8th for Sanity Connect

Discussion about querying and displaying featured posts in frontend, with some troubleshooting and guidance provided.

48 replies
Last updated: Nov 9, 2022
Hi need help, I want to show the sanity selected post in frontend but it's giving 4 different post ids
and i used
"selectPostOne": *[_type == "post" && references(^._id)]{
${postFields}
},
Nov 2, 2022, 6:25 AM
Hey
user X
! You can select a single post like this:
"selectPostOne": *[_type == "post" && references(^._id)][0]{
        ${postFields}
      },
Nov 2, 2022, 5:28 PM
Thanks it worked.
Nov 7, 2022, 9:06 PM
hi
user M
seems like it didn't work.. I guess the question might not be that clear. So we are trying to get a featured post information against a category + get all post against a category.Our all post feature seems to be working fine as we are referencing it to
references(^._id)
Unfortunately we aren't able to get the featured post fieldss and it gives weird data. (its giving is me 3 same random post information.
Nov 7, 2022, 9:18 PM
How are you indicating that a post is featured? Is it set as a field on your document?
Nov 7, 2022, 9:22 PM
yeah so against a category we have 3 reference post fields
Nov 7, 2022, 9:22 PM
then we have this query
Nov 7, 2022, 9:24 PM
Ok! I see now. If you're setting those references on a document you don't need to do an entire subquery. You can just use the
->
operator to expand them like this:
postReference->
Nov 7, 2022, 9:34 PM
sorry not sure how to write that.. 😞
Nov 7, 2022, 9:38 PM
In the same way that you've specified
_id
,
_type
, etc. in your projection, you'd add that dereferenced field. There are docs here that may help you understand.
Nov 7, 2022, 9:40 PM
*[_type == "movie"] {
  ...,
  "actors": actors[]{
    ...
    person->
  }
}

Nov 7, 2022, 9:53 PM
Sorry I am a bit new to Sanity.. so it's hard to understand.
Nov 7, 2022, 9:53 PM
No worries. That exact query won't work for you, since your data is structured differently.
Basically, you can remove all of the fields that you've defined with quotes/a subquery and replace them with the name of the field in your schema with an arrow after it. If you're still not sure what that means, you can take a look at
these docs. They explain how queries work much better than I can 🙂
Nov 7, 2022, 10:03 PM
ok, gotcha, something like this:
Nov 7, 2022, 10:06 PM
Exactly!
Nov 7, 2022, 10:07 PM
yeah that worked..
Nov 7, 2022, 10:07 PM
sorry one more question, is there a way to add those all in an array all the three references and output them on the frontend, as I don't want to individually check if it has a null or not?
Nov 7, 2022, 10:08 PM
ok got it
Nov 7, 2022, 10:13 PM
Great!
Nov 7, 2022, 10:15 PM
so i have written it down as this and it consoles me the values which is fine, but when i try to loop through it, it gives an error
item.postReferences.map is not a function, I have also defined postReferences?: Map<string, string>;
Nov 7, 2022, 10:30 PM
postReferences
is an object in that query, so you won't be able to map over it. I don't think you'll be able to coerce your data into an array using GROQ. You can keep that query as it is and use
Object.keys(results.postReferences).map(reference => { //your function here })
Nov 7, 2022, 10:41 PM
do i need to loop one more to get the other values?
Nov 7, 2022, 11:14 PM
You could do something like this to get the values:
Object.keys(results.postReferences).map(reference => { 
 const values = results.postReferences[reference]
})

Nov 7, 2022, 11:16 PM
yeah i did that, and thats what it returned above.
Nov 7, 2022, 11:19 PM
OK, then you can access the fields using dot notation.
Nov 7, 2022, 11:20 PM
OK, then you can access the fields using dot notation.
Nov 7, 2022, 11:20 PM
you mean this right {values.title}
Nov 7, 2022, 11:20 PM
Exaclty.
Nov 7, 2022, 11:20 PM
I did that too, but it was giving me an error of "*Cannot read property 'title' of null"*
Nov 7, 2022, 11:21 PM
so I have this
{allCategoryMenu.map((item) => {
        console.log(item.postReferences);

        return (
          <>
            {Object.keys(item.postReferences).map((reference) => {
              const values = item.postReferences[reference];
              return (
                <>
                  <div key="{values.slug}">{values.title}</div>
                </>
              );
            })}
          </>
        );
      })}
Nov 7, 2022, 11:24 PM
The promise likely hasn't resolved yet, so those values aren't defined when the code is evaluated. You can try checking to make sure the value is there before accessing title or try optional chaining like
value?.title
.
Nov 7, 2022, 11:27 PM
nope, this also didn't work. 😞
Nov 7, 2022, 11:31 PM
ok yeah it seemed to work .. why do we need "?" there
Nov 7, 2022, 11:32 PM
{allCategoryMenu.map((item) =&gt; { return (
&lt;&gt;
{Object.keys(item.postReferences).map((reference) =&gt; {
const values = item.postReferences[reference];
if (values?.title == null) return "";

return (
&lt;&gt;
&lt;article key="{values?.slug}"&gt;{values?.title}&lt;/article&gt;
&lt;/&gt;
);
})}
&lt;/&gt;
);
})}

if we don't want to show emtoy then we do it like this?
Nov 7, 2022, 11:40 PM
hi, could you let me know how I can check null against this array of post references.. as I couldn't like it to come inside the "object keys" loop.
Nov 8, 2022, 10:40 PM
user M
can you help me with this please.
Nov 9, 2022, 9:02 PM
user J
could you help me with this
Nov 9, 2022, 10:26 PM
Hey
user F
please don't tag people from the community if they're not involved in a thread. People will help you if they have the availability or an answer to contribute.
Nov 9, 2022, 10:38 PM
ok sorry about that. Didn't knew.
Nov 9, 2022, 10:38 PM
No worries, just want to keep the community comfortable for everyone! I can try to help out with your request later this afternoon.
Nov 9, 2022, 10:39 PM
I’m not sure I’m fully understanding, but if I am you have a couple options. First you could try filtering the initial array to not include null empty items at all (not totally sure if this will work):
{allCategoryMenu.map(item => {
  return (
    <>
      {Object.keys(item.postReferences).filter(Boolean).map(reference => {
        const values = item.postReferences[reference];
        return (
          <>
            <article key={values?.slug}>{values?.title}</article>
          </>
        );
      })}
    </>
  );
})}
Otherwise you can return
null
in the loop, something like this:
{allCategoryMenu.map(item => {
  return (
    <>
      {Object.keys(item.postReferences).map(reference => {
        const values = item.postReferences[reference];
        if (!values.title) return null;

        return (
          <>
            <article key={values?.slug}>{values?.title}</article>
          </>
        );
      })}
    </>
  );
})}

Nov 9, 2022, 10:39 PM
sure, thank you. Apologies once again.
Nov 9, 2022, 10:39 PM
{allCategoryMenuData.map((item) =&gt; {}
is there a way not even to get into the outer loop if there is a null as I have category printed in the first loop then articles in the second loop.
Nov 9, 2022, 10:43 PM
i have done it like this, but I had to add these 3 variables in my query to check it out here. Wondering if there is a way to loop through array to check if all are null.
Nov 9, 2022, 10:46 PM
hmm probably, 1 sec
Nov 9, 2022, 10:53 PM
Untested but you can try this, hopefully it’s answering what you’re trying to do, or get you closer..
Try using this as the
postReferences
in your groq query instead of your object version:
"postReferences": [postReference1->, postReference2->, postReference3->],
Then something like this in the js:

{allCategoryData
  // Filter out ones with no references
  .filter(item => item.postReferences.filter(Boolean).length !== 0)
  // All these should have at least one featured reference now
  .map(item => {
    return (
      <>
        {item.postReferences.map(reference => {
          return (
            <>
              <article key={reference?.slug}>{reference.title}</article>
            </>
          );
        })}
      </>
    );
  })}
Nov 9, 2022, 10:57 PM
I may have missed this in the thread above but you might be better off storing these as an array on the document instead of single objects.
Nov 9, 2022, 10:58 PM
ok yeah that worked
Nov 9, 2022, 11:03 PM
Awesome 🙂
Nov 9, 2022, 11:27 PM

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?