> To build or manage a Wix site with an AI agent, follow https://www.wix.com/headless/skill.md
> It builds a new Wix site or puts your own site online, from a prompt, and keeps changing it afterwards. The pages are code in any web technology, and Wix runs the backend.
> It works through the Wix plugin (the Wix MCP and the Wix skills), the Wix CLI or no Wix login, and puts the site live on Wix hosting or on another host.
> Business features include a store, bookings, events and tickets, a restaurant, a blog, forms, members and many more.
> Read the Wix skills online at https://www.wix.com/skills
> 
> Portal Navigation:
> 
> - Append `.md` to any URL under `https://dev.wix.com/docs/` to get its markdown version.
> - Pages are either content pages (article or reference text) or menu pages (a list of links to child pages).
> - To get a menu page, truncate any URL to a parent path and append `.md` (e.g. `https://dev.wix.com/docs/sdk.md`, `https://dev.wix.com/docs/sdk/core-modules.md`).
> - If a reference page seems to be missing its schema (parameters, return types, or type definitions), append `?schema=true` to its `.md` URL (e.g. `https://dev.wix.com/docs/contexts/contexts/stores/category-info/use-category-info-context.md?schema=true`).
> - Top-level index of all portals: https://dev.wix.com/docs/llms.txt
> - Full concatenated docs: https://dev.wix.com/docs/llms-full.txt

## Resource: Build a Data Source in Studio Two

## Article: Build a Data Source in Studio Two

## Article Link: https://dev.wix.com/docs/studio-two/code-your-site/code-model/data-sources/build-a-data-source-in-studio-two.md

## Article Content:

# Build a Data Source in Studio Two

A [Data Source](https://dev.wix.com/docs/studio-two/code-your-site/code-model/data-sources/about-data-sources.md) is implemented as a context provider manifest and a React provider component. The manifest declares the extension's contract, and the component implements its state and behavior.

Follow the instructions below to:

1. Add the Data Source files.
2. Declare the context provider contract.
3. Implement the provider component.
4. Refine the Data Source.
5. Check the Data Source.

## Step 1 | Add the Data Source files

Start with a generated Data Source so the file structure and registration are in place. For the full procedure, see [Add a Data Source Extension in Studio Two](https://dev.wix.com/docs/studio-two/code-your-site/code-model/data-sources/add-a-data-source-extension-in-studio-two.md).

You can find the generated files under `src/extensions/site/contexts/<provider-folder>/`:

- `<provider-folder>.extension.ts` contains the context provider manifest.
- `<provider-folder>.tsx` contains the React provider component.

For details about both files, see [Context Provider Extension Files and Code](https://dev.wix.com/docs/site-extensions/context-providers/context-provider-extension-files-and-code.md).

## Step 2 | Declare the context provider contract

Open `<provider-folder>.extension.ts`. The generated manifest uses `extensions.contextProvider()` and contains the following sections:

- `context.items` declares each value and function that ERCs can connect to.
- `data` declares configuration inputs that a Wix user sets on the Data Source.
- `resources` points to the provider component and names its exported context hook.

For example, the generated counter declares a count value, functions for changing it, and an initial count input:

```ts
import { extensions } from '@wix/custom-extensions';

export default extensions.contextProvider({
  id: 'a1b2c3d4-e5f6-7890-abcd-ef1234567890',
  name: 'my-data-source',
  type: 'companionApp.myDataSource',
  displayName: 'my-data-source',
  context: {
    items: {
      count: {
        dataType: 'number',
        displayName: 'Counter current value',
      },
      decrement: {
        dataType: 'function',
        displayName: 'Decrement counter value by 1',
        function: {},
      },
      increment: {
        dataType: 'function',
        displayName: 'Increment counter value by 1',
        function: {},
      },
      setCount: {
        dataType: 'function',
        displayName: 'Set counter value to a specific number',
        function: {
          parameters: [
            {
              dataType: 'number',
              displayName: 'New counter value',
            },
          ],
        },
      },
    },
  },
  data: {
    initialCount: {
      dataType: 'number',
      defaultValue: 0,
      deprecated: false,
      displayName: 'Initial Count',
    },
  },
  resources: {
    client: {
      url: './extensions/site/contexts/my-data-source/my-data-source.tsx',
    },
    contextSpecifier: {
      hook: 'useCounterContext',
    },
  },
});
```

Keep the generated `id` stable after Wix users connect elements to the Data Source. Update `displayName`, `context.items`, and `data` to describe your Data Source. The editor lists each item in `context.items` by its `displayName`, so make the name clear on its own.

The generated manifest has no module specifier. Add one under `resources.contextSpecifier`, starting with `@/` and followed by the provider folder name:

```ts
contextSpecifier: {
  hook: 'useCounterContext',
  moduleSpecifier: '@/my-data-source',
},
```

The module specifier must be unique in your site. After Wix registers the Data Source, don't change it. For the rules, see [Context Provider Resources Reference](https://dev.wix.com/docs/site-extensions/context-providers/context-provider-resources-reference.md#module-specifier).

For every field, see [About the Context Provider Manifest](https://dev.wix.com/docs/site-extensions/context-providers/about-the-context-provider-manifest.md).

## Step 3 | Implement the provider component

Open `<provider-folder>.tsx`. Implement every value and function declared in `context.items`, and accept each configuration input you use from `data` as a prop.

The generated counter holds its count in React state and provides the count and its functions through React Context:

```tsx
import { createContext, useContext, useState } from 'react';
import type { ReactNode } from 'react';

export interface CounterContextType {
  count: number;
  decrement: () => void;
  increment: () => void;
  setCount: (count: number) => void;
}

export interface CounterProviderProps {
  children?: ReactNode;
  initialCount: number;
}

const CounterContext = createContext<CounterContextType | undefined>(undefined);
CounterContext.displayName = 'CounterContext';

export function useCounterContext(): CounterContextType {
  const context = useContext(CounterContext);
  if (!context) {
    throw new Error('useCounterContext must be used within a CounterContextProvider');
  }

  return context;
}

function CounterContextProvider({
  children,
  initialCount,
}: CounterProviderProps): ReactNode {
  const [count, setCount] = useState(initialCount || 0);

  const increment = () => {
    setCount((current) => current + 1);
  };

  const decrement = () => {
    setCount((current) => current - 1);
  };

  const api = {
    count,
    decrement,
    increment,
    setCount,
  };

  return (
    <CounterContext.Provider value={api}>{children}</CounterContext.Provider>
  );
}

CounterContextProvider.displayName = 'CounterContextProvider';

export default CounterContextProvider;
```

Export the hook named by `resources.contextSpecifier.hook`, and export the provider component as the default export. A Wix user can connect an ERC's props to the exposed values and functions in the editor. An ERC can also [call the hook in its own code](https://dev.wix.com/docs/studio-two/code-your-site/code-model/editor-react-components/use-a-data-source-in-an-editor-react-component-in-studio-two.md).

## Step 4 | Refine the Data Source

Keep each Data Source focused on one domain or feature. Expose state values together with the functions that change them, such as a selected teammate ID and a `selectTeammate` function.

Attach the Data Source at the narrowest scope that needs it. A Data Source attached to a container affects only the components nested in it, while one attached to a page can affect every connected component on that page.

Separate frequently changing values from stable values when possible. Every connected ERC that receives an updated value renders again.

Derive values from other state instead of storing them separately. `useMemo` recalculates a derived value only when the state it depends on changes:

```tsx
import { useMemo, useState } from 'react';

const [teammates, setTeammates] = useState<Teammate[]>([]);
const [department, setDepartment] = useState('all');

const filteredTeammates = useMemo(
  () =>
    teammates.filter(
      (teammate) =>
        department === 'all' || teammate.department === department,
    ),
  [teammates, department],
);
```

### Expose values that are ready to connect

Editor binding passes an item to a property as is, apart from converting between compatible data types. Binding has no expressions, so a Wix user can't compare or combine items directly. Compute each value in the provider and expose it in the form an element needs.

For example, to show a banner once a site visitor has clicked 10 times, don't expose only `count` and expect the banner to compare it. Expose a boolean, such as `isGoalReached`, as well:

```tsx
const isGoalReached = count >= 10;

const api = {
  count,
  isGoalReached,
  increment,
};
```

Declare the boolean in `context.items` with `dataType: 'booleanValue'`. To show the banner only when `isGoalReached` is true, a Wix user adds a condition in the banner's **Settings > Advanced > Conditional visibility**. When a configuration input sets the goal, give the input a `defaultValue` and handle a missing value in the provider, so the banner works before a Wix user sets it.

### Load data without hiding the page

A Data Source often loads data when it first renders, for example with a Wix SDK call. Keep rendering `children` while the data loads. If the provider renders nothing while it waits, every element in the area it's attached to disappears until the data arrives, including elements that aren't connected to it.

Start with placeholder values, load the data in an effect, and expose an `isLoading` boolean so connected elements can show a loading state:

```tsx
import { createContext, useContext, useEffect, useState } from 'react';
import type { ReactNode } from 'react';
import { items } from '@wix/data';

interface Teammate {
  id: string;
  name: string;
  role: string;
}

interface TeamContextType {
  teammates: Teammate[];
  isLoading: boolean;
  hasError: boolean;
}

interface TeamProviderProps {
  children?: ReactNode;
  department?: string;
}

const TeamContext = createContext<TeamContextType | undefined>(undefined);

export function useTeamContext(): TeamContextType {
  const context = useContext(TeamContext);
  if (!context) {
    throw new Error('useTeamContext must be used within a TeamContextProvider');
  }

  return context;
}

function TeamContextProvider({ children, department = 'all' }: TeamProviderProps): ReactNode {
  const [teammates, setTeammates] = useState<Teammate[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [hasError, setHasError] = useState(false);

  useEffect(() => {
    let isCurrent = true;
    setIsLoading(true);
    setHasError(false);

    items
      .query('Teammates', {
        filter: department === 'all' ? {} : { department },
      })
      .then((result) => {
        if (!isCurrent) return;
        setTeammates(
          result.items.map((item) => ({
            id: item._id,
            name: item.name,
            role: item.role,
          })),
        );
      })
      .catch(() => {
        if (isCurrent) setHasError(true);
      })
      .finally(() => {
        if (isCurrent) setIsLoading(false);
      });

    return () => {
      isCurrent = false;
    };
  }, [department]);

  return (
    <TeamContext.Provider value={{ teammates, isLoading, hasError }}>
      {children}
    </TeamContext.Provider>
  );
}

export default TeamContextProvider;
```

The example shows several practices for loaded data:

- The effect depends on `department`, a configuration input, so the provider loads again when a Wix user changes it.
- `isCurrent` stops a slow, earlier request from overwriting the results of a newer one.
- The provider maps each record to the fields that elements display, rather than exposing the full objects the API returns. Declare the same fields in the manifest, as the list example in [Context Reference](https://dev.wix.com/docs/site-extensions/context-providers/context-reference.md#arrays) shows.
- A failed request sets `hasError`, so connected elements can show an error state.

Wix authenticates SDK calls from a provider for you, so you don't set up authentication. The calls run with the site visitor's permissions. For example, the `Teammates` collection must let site visitors read its items. For an operation that site visitors aren't allowed to do, call an [HTTP endpoint](https://dev.wix.com/docs/studio-two/code-your-site/build-a-custom-backend/http-endpoints/about-http-endpoints.md) that runs it in the backend with elevated permissions. Any site visitor can call an endpoint, so the endpoint must check the caller and validate the input before the elevated call, as [Build an HTTP Endpoint in Studio Two](https://dev.wix.com/docs/studio-two/code-your-site/build-a-custom-backend/http-endpoints/build-an-http-endpoint-in-studio-two.md) shows.

### Check the manifest against the code

Check that:

- Every `context.items` entry has a matching value or function in the provider.
- Every configuration input used by the component has a matching `data` entry and prop.
- Function parameters and responses match between the manifest and TypeScript implementation.
- The `resources.client.url` and `contextSpecifier.hook` values match the provider file and export.
- `contextSpecifier.moduleSpecifier` starts with `@/`.

If an ERC doesn't receive an expected value, check that the Data Source is attached above the ERC, the ERC prop is connected to the correct context item, and both manifests use compatible data types.

## Step 5 | Check the Data Source

To check the Data Source:

1. Switch to the **Design** tab.
2. In the **Layers** panel, select the page, container, or section that should have access to the Data Source. Then select **More Actions > Connect to Data**. The element's **Settings** panel opens to its **Data sources** section.
3. Click **Connect Source**, then select your Data Source under **Custom code**.
4. If your Data Source declares `data` inputs, click the **Manage** button that names your Data Source in the floating toolbar, or the row of the connected source, and set them. Each input appears with its `displayName`. For example, `initialCount` appears as **Initial Count**.
5. Add or select an element inside the area you selected in step 2. Open its **Settings** panel, and click the connect icon next to the property you want to connect.
6. In the **Connect to Data** panel, select the same Data Source under **Source**, then select an item from `context.items` under **Field**. **Field** lists only the items whose data type matches the property, and selects the item automatically when only one matches.
7. Click **Apply**.

The connected element shows the value from your Data Source. To find the page, container, or section in the **Layers** panel, see [Studio Two Editor: Working with Layers](https://support.wix.com/en/article/studio-two-editor-working-with-layers). For the **Connect Source** panel, see [Connect to Source](https://support.wix.com/en/article/connect-to-source).

When the Data Source behaves as expected, click **Publish** to ship it with the site.

## See also

- [About Data Sources](https://dev.wix.com/docs/studio-two/code-your-site/code-model/data-sources/about-data-sources.md)
- [Add a Data Source Extension in Studio Two](https://dev.wix.com/docs/studio-two/code-your-site/code-model/data-sources/add-a-data-source-extension-in-studio-two.md)
- [Context Provider Extension Files and Code](https://dev.wix.com/docs/site-extensions/context-providers/context-provider-extension-files-and-code.md)
- [Context Reference](https://dev.wix.com/docs/site-extensions/context-providers/context-reference.md): the `context` section of a context provider manifest
- [Data Reference](https://dev.wix.com/docs/site-extensions/context-providers/data-reference.md)