Fetch data from Sanity content management system in an Expo app
Published: 2024-03-11 20:04:36

Have you used the Sanity content management system before? 
Sanity is a powerful content management system (CMS) that allows developers to easily manage and organize content for their applications. In this article, we'll explore how to integrate Sanity with an Expo app, enabling you to fetch existing data from Sanity.

Expo is an open-source framework and platform for building universal React applications, with a focus on mobile development. It allows developers to create high-quality iOS and Android apps using JavaScript and React Native

Let's create a project that fetches data from Sanity in an Expo app. We'll start by setting up a new Sanity project, defining schemas, deploying it, and then creating an Expo app to fetch and display the data.

## Setting up Sanity:

**Installing Sanity CLI:**

Open your terminal or command prompt.

Run the following command to install the Sanity CLI globally:
`npm install -g @sanity/cli`
Initialize a new Sanity project:
Run the following command to initialize a new Sanity project:
`sanity init`
Follow the prompts to create a new project. You can choose the default options for most settings.

**Define schemas:**
In your Sanity project directory, navigate to the schemas directory.
Create a new file named post.js.
Define the schema for a blog post inside post.js:

```
// schemas/post.js

export default {
    name: 'post',
    title: 'Post',
    type: 'document',
    fields: [
      {
        name: 'title',
        title: 'Title',
        type: 'string',
      },
      {
        name: 'body',
        title: 'Body',
        type: 'text',
      },
    ],
  };
```
  

**Deploy the Sanity project:**
Once you've defined your schemas, deploy your Sanity project to make the schemas and data accessible via an API:
Follow the prompts to deploy your project.

`sanity deploy`
The above command is to be run inside the sanity folder that resulted from initializing sanity above with `sanity init`

## Creating the Expo app

Initialize a new Expo app

In a separate directory, create a new Expo app:

`expo init sanityExpoApp`
Choose the blank template when prompted.

**Install required packages:**

Navigate into the newly created Expo app directory:
`cd sanityExpoApp`
Install the necessary packages for fetching data from Sanity:
npm install @sanity/client
Set up Sanity client:
Create a new file named sanityClient.js in the root of your Expo project directory.
Configure a Sanity client inside sanityClient.js:

```
// sanityClient.js

import sanityClient from '@sanity/client';

const client = sanityClient({
  projectId: 'your-project-id',
  dataset: 'your-dataset-name',
  useCdn: true, // Enable the Content Delivery Network (CDN) for faster responses
});

export default client;
```

Replace 'your-project-id' and 'your-dataset-name' with your actual Sanity project ID and dataset name.

Fetch data in the Expo app:
Open the App.js file in your Expo project directory.
Replace the existing code with the following code:

```
// App.js

import React, { useState, useEffect } from 'react';
import { View, Text } from 'react-native';
import client from './sanityClient';

const App = () => {
  const [posts, setPosts] = useState([]);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const result = await client.fetch('*[_type == "post"]');
        setPosts(result);
      } catch (error) {
        console.error('Error fetching data:', error);
      }
    };

    fetchData();
  }, []);

  return (
    <View>
      <Text>Posts:</Text>
      {posts.map((post, index) => (
        <View key={index}>
          <Text>{post.title}</Text>
          <Text>{post.body}</Text>
        </View>
      ))}
    </View>
  );
};

export default App;
```

Run the Expo app:
Run your Expo app using the following command:
`expo start`