0

I'm creating a web application using sanity. I added 'likes' field which is a number, to my post schema. I can see likes on my desk, but when I query *[_type == 'post'] I don't see likes field. Also, when I try to increment the field 'likes' using patch function, client complaints that the field does not exist. How can I fix it?

Sachin Titus
  • 1,960
  • 3
  • 23
  • 41

1 Answers1

0

I imagine these issues are due to data not yet being in your posts. Let's break it down:

Patch error

As you can't increment an undefined/null value, you have to first run setIfMissing on your likes field to make sure it exists. Here's some pseudo code:

client
  .patch(postId)
  .setIfMissing({ likes: 0 }) // ensure likes exist
  .inc({ likes: 1 }) // And only then increment it
  .commit()

Field not appearing in queries

By default, GROQ won't return empty values. That means that, if your posts don't have likes set, you won't even see this property in the data returned from the API.

IF you need likes to show up, you can use GROQ's coalesce function to provide a default value to likes. Here's a sample query:

*[_type == "post"]{
  ...,
  // Default likes to 0
  "likes": coalesce(likes, 0),
}

Hope this helps

Henrique Doro
  • 436
  • 4
  • 7