DEV Community

Sebastian Duta
Sebastian Duta

Posted on

How To Use Supabase Database in React Native - Complete Guide

React Native is a popular platform for creating mobile applications that are compatible with both iOS and Android. It is a great choice for developing cross-platform applications. In this tutorial, we will learn how to use Supabase, an open-source database, in our React Native app. We will be creating a basic todo app and will include code examples with functional components.

Setting up the React Native app

To get started, we need to create a new React Native project. We can do this by running the command react-native init TodoApp. This will create a new folder called TodoApp with the React Native code inside.

Adding all Supabase dependencies

Next, we need to install the Supabase dependencies. This can be done by running the command npm install @supabase/supabase-js followed by npm install @supabase/supabase-react-native. This will install all the necessary packages for us to use Supabase in our React Native app.

Setting up Supabase read and write access rules

Before we can write to and read from Supabase, we need to set up some access rules. This is done by going to the Supabase dashboard and creating a new project. Once we have created the project, we need to go to the access rules section and set up read and write rules that will allow our app to access our database.

Writing to Supabase from React Native

Now that we have set up the access rules, we can start writing to Supabase from our React Native app. To do this, we need to first create a new component to handle the writing. This component will contain a form that will allow us to enter the todo item and a button that will submit the data to Supabase.

import React from 'react';
import { View, TextInput, Button } from 'react-native';

export default class AddTodo extends React.Component {
  state = {
    todoText: ''
  };

  handleSubmit = () => {
    // code to submit to Supabase
  };

  render() {
    return (
      <View>
        <TextInput
          value={this.state.todoText}
          onChangeText={text => this.setState({ todoText: text })}
        />
        <Button title="Submit" onPress={this.handleSubmit} />
      </View>
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

In the handleSubmit function, we can use the supabase package to write the data to our database. We can do this by using the insert() method and passing in the table name, the data, and an optional parameter to return the inserted data.

import { insert } from '@supabase/supabase-js';

handleSubmit = () => {
  const data = {
    text: this.state.todoText
  };

  insert('todos', data, { returning: true })
    .then(result => {
      const todo = result.returning[0];
      // code to add the todo to the list
    })
    .catch(err => {
      console.log(err);
    });
};
Enter fullscreen mode Exit fullscreen mode

Reading single objects from Supabase

Once we have written the data to Supabase, we need to be able to read it back out. To do this, we can use the select() method. This method takes in a table name, a query, and an optional parameter to return the selected data.

import { select } from '@supabase/supabase-js';

readTodo = (id) => {
  select('todos', {
    where: {
      id
    },
    returning: true
  })
    .then(result => {
      const todo = result.returning[0];
      // code to update the UI
    })
    .catch(err => {
      console.log(err);
    });
};
Enter fullscreen mode Exit fullscreen mode

Reading & displaying lists of objects

In addition to reading single objects, we may want to read a list of objects from our database. To do this, we can use the select() method with a limit parameter. This parameter allows us to specify the number of objects that we want to retrieve. We can also use the offset parameter to paginate our results.

import { select } from '@supabase/supabase-js';

readTodos = (offset) => {
  select('todos', {
    limit: 10,
    offset,
    returning: true
  })
    .then(result => {
      const todos = result.returning;
      // code to update the UI
    })
    .catch(err => {
      console.log(err);
    });
};
Enter fullscreen mode Exit fullscreen mode

Listening to real-time updates

In addition to reading and writing data, Supabase also supports real-time updates. We can listen for updates by using the listen() method. This method takes in a table name, a query, and a callback function that will be called when there is an update.

import { listen } from '@supabase/supabase-js';

listenTodos = () => {
  listen('todos', {}, (err, data) => {
    if (err) {
      console.log(err);
    } else {
      // code to update the UI
    }
  });
};
Enter fullscreen mode Exit fullscreen mode

Batch updates to improve performance

If we need to update multiple objects at once, we can use the update() method. This method takes in a table name, a query, and an object containing the values we want to update. This is an efficient way to update multiple objects at once and can improve performance.

import { update } from '@supabase/supabase-js';

updateTodos = (ids, completed) => {
  update('todos', {
    where: {
      id: ids
    },
    set: {
      completed
    },
    returning: true
  })
    .then(result => {
      const todos = result.returning;
      // code to update the UI
    })
    .catch(err => {
      console.log(err);
    });
};
Enter fullscreen mode Exit fullscreen mode

How to Paginate Lists from Supabase DB

Finally, we may want to paginate our lists from Supabase. To do this, we can use the offset parameter in the select() method. This parameter allows us to specify the number of objects to skip before returning the results. We can use this to paginate our results and display them in pages.

import { select } from '@supabase/supabase-js';

readTodos = (pageNumber) => {
  const offset = pageNumber * 10;

  select('todos', {
    limit: 10,
    offset,
    returning: true
  })
    .then(result => {
      const todos = result.returning;
      // code to update the UI
    })
    .catch(err => {
      console.log(err);
    });
};
Enter fullscreen mode Exit fullscreen mode

Conclusion

In this tutorial, we learned how to use Supabase in our React Native app template. We went through the process of setting up the React Native app, adding all the necessary dependencies, setting up the access rules, writing to Supabase, reading single objects, reading and displaying lists of objects, listening to real-time updates, batch updates to improve performance, and paginating lists from Supabase. We also included code examples with functional components for each step of the process. We hope this tutorial has been helpful in your journey to creating a React Native app with Supabase, that works for both Android and iOS.

Top comments (0)