> 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`).
> - 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.

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. ERCs connect to the exposed values and functions through editor binding. They don't call the hook directly.

## 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],
);
```

When a Data Source loads information based on a configuration input, accept the input as a provider prop and load the resource when that value changes. Expose loading and error state when connected ERCs need to represent those states.

Finally, 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.

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)