How to define initialValue for a field based on current route in Sanity

7 replies
Last updated: Jan 25, 2022
Hi! Been getting back into Sanity now with some new features to develop, I'm stuck trying to define a
initialValue
for a field based on the current route. Is there any sane way of getting the current route values from an
initialValue
function, other than parsing
window.location
manually?The case is my
deskStructure
groups a type of document based on the
application
they belong to. Which means when I create a new document in a specific
application
document group I want the document to have the
application
reference field prefilled. Example of a route:
/desk/changelog;restaurant;315...a9f%2Ctemplate%3Dchangelog
in which
restaurant
is the
application.slug
which I want to retrieve. Hope this makes sense, somehow!
Jan 24, 2022, 2:55 PM
    S.listItem()
      .title("Changelog")
      .child(
        S.list()
          .title("Applications")
          .items([
            S.listItem()
              .title("Restaurant")
              .child(
                S.documentTypeList("changelog")
                  .filter('application->slug.current == "restaurant"')
                  .title("Changelogs")
              ),
            S.listItem()
              .title("iOS")
              .child(
                S.documentTypeList("changelog")
                  .filter('application->slug.current == "ios"')
                  .title("Changelogs")
              ),
          ])
      ),
The deskStructure, for further clarity
Jan 24, 2022, 2:57 PM
Currently have it working with this:
initialValue: async (params) => {
  const slug = window.location.pathname.split(";")[1];
  const groupQuery = `*[_type == "application" && slug.current == "${slug}"][0]`;
  const { _id: applicationId } = await client.fetch(groupQuery);
  return { _ref: applicationId };
},
Which feels a bit flaky, but works for now.
Jan 24, 2022, 3:08 PM
Encountered an issue with this approach, which causes the field to appear unpopulated, but on focus of any field pops up as properly populated. See video πŸ™‚
Jan 24, 2022, 3:17 PM
Hardcoding the id means you no longer have to do an async call to get the reference based on the selected slug.
Jan 24, 2022, 4:37 PM
Here's a little example of this technique in use.
Jan 24, 2022, 4:39 PM
Ahh alright, was looking at initialValueTemplates but couldn't see how it would solve it, until now. Many thanks for the detailed response ❀️
Jan 25, 2022, 7:49 AM
Let us know if you have any other questions πŸ™‚.
Jan 25, 2022, 10:03 AM

Sanity– build remarkable experiences at scale

The Sanity Composable Content Cloud is the 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?

Categorized in