#Save query to a prop available globally on build time..

6 messages · Page 1 of 1 (latest)

warm raptor
#

I am currently working on a headless Wordpress site, I have a quick question!

Is there a way I can get a query for my cssVariables and load and store them statically on buildtime?

Would love If I can get and save the initial build time query and not have to query every page load for it..

For example,

const response = await fetch(${import.meta.env.WORDPRESS_API_URL}, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
query: query wpCssVariables { cssVariables } ,
}),
})
const { data } = await response.json()
const cssVariables = data.cssVariables

I would like to save data as a prop and be able to use it everywhere, from the props..

latent wolfBOT
#

Hi @warm raptor. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

To save a query result globally at build time and make it available throughout your Astro project, you can use Astro's Content Collections API. This approach allows you to fetch the data once during the build process and use it across your site without querying on every page load. Here's how you can achieve this:

  1. First, create a content collection for your CSS variables. In your project, create a file at src/content/config.ts (if it doesn't exist already) and add the following:
import { defineCollection, z } from 'astro:content';

const cssVariablesCollection = defineCollection({
  type: 'data',
  schema: z.object({
    cssVariables: z.string()
  })
});

export const collections = {
  'cssVariables': cssVariablesCollection,
};
  1. Next, create a loader for this collection. In the same src/content/config.ts file, modify the cssVariablesCollection to include a loader:
const cssVariablesCollection = defineCollection({
  type: 'data',
  schema: z.object({
    cssVariables: z.string()
  }),
  loader: async () => {
    const response = await fetch(`${import.meta.env.WORDPRESS_API_URL}`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        query: `
          query wpCssVariables {
            cssVariables
          }
        `,
      }),
    });
    const { data } = await response.json();
    return [{ id: 'wordpress', cssVariables: data.cssVariables }];
  }
});
  1. Now, you can access this data in any of your Astro components or pages using the getEntry function from astro:content. Here's an example:
---
import { getEntry } from 'astro:content';

const cssVariablesEntry = await getEntry('cssVariables', 'wordpress');
const { cssVariables } = cssVariablesEntry.data;
---

<style set:html={cssVariables}></style>
#

<!-- Rest of your component -->


This approach fetches the CSS variables once at build time and makes them available throughout your project. The data is stored statically and doesn't require querying on each page load.

For more information on using Content Collections in Astro, you can refer to the [Astro Content Collections documentation](<https://docs.astro.build/en/guides/content-collections/>).

Remember to adjust the schema and loader function according to the actual structure of your CSS variables data.

[Astro Content Loader API](<https://docs.astro.build/en/reference/content-loader-reference/#_top>) provides more details on how to create custom loaders for your content collections.
----------------------
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
----------------------
#

@warm raptor Kapa.ai is still learning and improving, please let me know how I did by reacting below.

warm raptor
#

why is this not registering my collection?

import type { Loader, LoaderContext } from 'astro/loaders'
import { z } from 'astro:content'

// Define any options that the loader needs
export function myLoader(options: { endpoint: string }): Loader {
// Configure the loader

// Return a loader object
return {
name: 'my-loader',
// Called when updating the collection.
load: async (context: LoaderContext): Promise<void> => {
const response = await fetch(options.endpoint, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
query: query wpCssVariables { cssVariables } ,
}),
})

  const { data } = await response.json()


},
// Optionally, define the schema of an entry.
// It will be overridden by user-defined schema.
schema: async () =>
  z.object({
    cssVariables: z.string(),
  }),

}
}