Home > Back-end >  How can I return null if the data doesn't exist
How can I return null if the data doesn't exist

Time:07-09

how can I use something like if(!testimonials) return nullfor all the data that I pass. it just shows empty array for now. I don't know where to use "if-else" rule.

aboutus.tsx

export const getServerSideProps = async ({ params }: any) => {
  
  const query = `{
  'stats': *[ _type == "stats"] {
           _id,
        title,
        stat,
        icon
  },
  'testimonials': *[ _type == "testimonials"] {
    _id,
        description,
        author,
        job,
  },
  'clients': *[ _type == "clients"] {
    _id,
        client,
        mainImage,
  },
}`;
  const props = await sanityClient.fetch(query);

  return { props: { 
     testimonials: props.testimonials,
     clients: props.clients,
     stats: props.stats,
   } 
  }; 
  
};

const aboutus = ({ testimonials, clients , stats}: any) => {
  return (
    <>
      <AboutComponent
        testimonials={testimonials}
        clients={clients}
        stats={stats}
      />
    </>

thank you for your help!

CodePudding user response:

You can probably use the ternary operator, if the testimonials attribute can be null:

<AboutComponent
        testimonials={!testimonials ? null : testimonials}
        clients={clients}
        stats={stats}
      />

CodePudding user response:

I don't know if I understand correctly, but it looks like you want this component to be dynamic

you can use this

<>
  {!!testimonials && (
       <AboutComponent
        testimonials={testimonials}
        clients={clients}
        stats={stats}
      />
  )}
</>

this way you transform "testimonials" into boolean and only show if "testimonials" is true

if you need the ELSE you can do it like this

<>
  {testimonials ? (
       <AboutComponent
        testimonials={testimonials}
        clients={clients}
        stats={stats}
      />
  ) : (
    <h1>testimonials does not exist</h1>
  )}
</>
  • Related