Slice zone fetch static data from Page that's using the slice

Hello! I'm wondering if there's any way for Slices to fetch data from its own Page that's using the Slice?

Example situation

I have 2 Page types called the following:

  • Samsung phone product (API ID: samsung_phone_product)
  • Motorola phone product (API ID: motorola_phone_product)

These 2 page types have similar static data:

  • Model name (data.model_name)
  • Year manufactured (data.year)
  • Processor (data.processor)
  • Battery (data.battery)

Then I have a Slice called ProductDetails. This slice is empty, doesn't have any input field. In the code, I style this Slice so that it looks modern and polished, but the style varies depending on the phone brand. Something like the following:

<div className={props.brand === 'samsung_phone_product'? 'samsungStyle' : 'motoStyle'}> 
  <h1>{props.brand === 'samsung_phone_product' ? 'Samsung' : 'Motorola'} </h1>
  <p>{props.model_name}</p>
  <p>{props.year}</p>
  <p>{props.processor}</p>
  <p>{props.battery}</p>
</div>

I set the 2 Page types (Samsung and Motorola product pages) to use ProductDetails slice.

Now let's say in the Prismic Dashboard, I created a new "Samsung phone product" page. I input the static data as the following:

  • UID: galaxys99
  • Model name: "Galaxy s99"
  • Year: 2080
  • Processor: "Snapturtle"
  • Battery: "9000mAh"

I want the ProductDetails slice to be able to fetch these static data, along with the page type API ID (samsung_phone_product)

And let's say I created a "Motorola phone product" page. I input the static data as the following:

  • UID: motoedge55
  • Model name: "Moto edge 55"
  • Year: 2075
  • Processor: "Kryptonite"
  • Battery: "8000mAh"

I also want the ProductDetails to be able to fetch these static data correctly along with the page type API (motorola_phone_product)

Is there any way I can do this? Any help or tips would be appreciated! Thank you!

Hey @epochdevelectronics,

There are two ways to do this. If you're using React/Next.js, you can pass arbitrary data to your slices using the context prop:

So, in your page.js file, you could pass the phone data into your <SliceZone> and then access that data on the slice level:

import { createClient } from "@/prismicio";

export default async function Page({ params }) {
  const client = createClient();

  const page = await client.getByUID("samsung_phone_product", params.uid);

  return (<SliceZone
           slices={page.data.slices}
           components={components}
           context={page}
          />);
}

The other option is with mapSliceZone():

This way you can query data for each slice. However, it's probably excessively complicated for your use case.

Let me know if you have any other questions!

Sam

Hi @samlittlefair ,

I used your first method of using context prop and confirmed it worked. Thank you very much for your help!

1 Like

Awesome!