React with Thin

Learn how to add Thin Backend to your existing react application

1. Introduction

This guide covers how to use Thin as the Backend for your existing react application.

If it's the first time you're using Thin, it's best to check out the Creating Your First Project instead.

2. Install Packages

To use Thin install the thin-backend and thin-backend-react packages into your project:

npm install thin-backend thin-backend-react

3. Init

Now that we have installed the Thin Backend packages, we need to call initThinBackend from the entrypoint of the app to initalize Thin.

import { initThinBackend, ensureIsUser } from 'thin-backend';
import { ThinBackend } from 'thin-backend-react';

// This needs to be run before any calls to `query`, `createRecord`, etc.
initThinBackend({
    // This url is different for each backend, you can find the backend url in the project documentation
    host: 'https://<YOUR PROJECTS BACKEND_URL>'
});

// React entrypoint component
function App() {
    // The `requireLogin` triggers a redirect to the login page if not logged in already
    return <ThinBackend requireLogin>
        <div>Hello World</div>
    </ThinBackend>
}


// Start the React app
ReactDOM.render(<App/>, document.getElementById('app'));

The <ThinBackend requireLogin> in the above code makes sure that the user is logged in. If the user is not logged in yet, it will redirect to the login page.

Now your react application is connected to your Thin Backend and you can now use Thin Backend for accessing your database and managing auth.

4. Installing Types (Optional)

Thin Backend generates TypeScript Type Definitions based on your database schema. This catches most runtime errors ahead of time, while providing really nice autocompletion in VSCode and other editors.

The custom Types can be installed into a project by installing a custom npm package. This npm package is specifically generated for your project and tagged with a secret url, so only you can access it.

To install your project's Types, open the Schema Designer. Click the Type Definitions tab. Now you see a npm install .. command:

Run this command locally in your project directory. After that the types will be automatically available in your project.

When you make changes to the database schema, a new type definition package will be generated. To use the latest types, open the Type Definitions tab again and install the latest package listed there.

5. Retrieving the Current User

A good starting point is to display the current logged in user and a logout button in your app. You can use useCurrentUser() for this:

// Add these imports:
import { logout } from 'thin-backend';
import { ThinBackend, useCurrentUser } from 'thin-backend';

function UserStatus() {
    // Use the `useCurrentUser()` react hook to access the current logged in user
    // Returns `null` while the user is being fetched
    const user = useCurrentUser();

    return <div>
        {user?.email}

        <button onClick={logout}>Logout</button>
    </div>
}

// Don't forget to mount the `<UserStatus/>` component from somewhere
// in your app:

function App() {
    return <ThinBackend requireLogin>
        <UserStatus />
    </ThinBackend>
}

The logout function used in the onClick is provided by Thin Backend. It deletes the locally stored JWT for the current user session and then redirects the user back to the login page.

The useCurrentUser() is real-time, so when e.g. the user's email or profile picture changes, this will automatically trigger a re-render of the react component with the new user object.

6. Fetching Data

You can use the useQuery hook to access your project's database. Let's say your building a todo list app and you've previously created a todos table in the Schema Designer. The following code will show all todos:

// Add these imports
import { query } from 'thin-backend';
import { useQuery } from 'thin-backend-react';

function TodoList() {
    const todos = useQuery(query('todos').orderByDesc('createdAt'));

    if (todos === null) {
        return <div>Loading ...</div>;
    }

    return <div>
        {todos.map(todo => <div>{todo.title}</div>)}
    </div>
}

The useQuery(query('todos')) call in our TodoList sets up a subscription behind the scences. Whenever the result set of our query('todos') we fired here changes, it will trigger a re-render of our component.

7. Writing Data

You can call createRecord('sometable', someObject) insert something into your database:

// Add this import
import { createRecord, getCurrentUserId } from 'thin-backend';

function NewTodoButton() {
    function addTodo(event) {
        createRecord('todos', {
            title: window.prompt('Enter a title:') || '',
            userId: getCurrentUserId()
        });
    }

    return <button onClick={addTodo}>Add Todo</button>
}

Check out the Database Guide for a full list of all database operations you can do with Thin.

Next: Database Guide

Community

If you need any help or input, feel free to ask in the Thin Community Forum.

Check out the React Template Projects on GitHub: