šŸ›“

Syncing all of your existing React State to the Cloud

Created
Nov 16, 2021 8:37 PM
Tags
frontendcloudstate

For this tutorial, we'll explore how you could sync the state you'd normally keep locally in-memory (with useState) to the cloud (with useCloudState)

We'll be using the todo-react repo by Mozilla Developer Network and extend it.

Prerequisites

1. Setting up the code base

We'll clone the repository, and install the dependencies so we have a good starting point

$ git clone https://github.com/mdn/todo-react todo-react-tutorial
$ cd todo-react-tutorial
$ yarn
$ yarn start # you should be able to see the todo app started on port 3000

2. Install the Cloud State CLI

Using the CLI, you can create a new Cloud State app instantly. If you haven't installed the CLI before, you could run the following command. If you already have it, you can skip this step.

$ curl https://raw.githubusercontent.com/usecloudstate/cli/main/install.sh | sh

Adding Cloud State

1. Install Cloud State dependencies

$ yarn add @usecloudstate/react-core @usecloudstate/react-web

2. Provision a new backend

You can use cloudstate create to create a new backend for for your app.

$ cloudstate create

Verifying your session with Cloud State server...
Session verified. āœ…
Creating a new app...
App Name: todo-react-tutorial
App Description: My awesome app
Origin: http://localhost:3000
Allow public signup?: yes
āœ… Your new app is created.
App ID: solitary-bush-KOaZZPK0
Name: todo-react-tutorial
Description: My awesome app
Origin: http://localhost:3000
Allow self signup: true
šŸ’” Hint to setup your app: $ cloudstate setup <path>

3. Initialize the Cloud State client in your App

You'll need to do the initialization as early as possible in your App. In the mdn-react-tutorial project, this would be in the App.js file.

See this commit for the change.

// 1. Import the two dependencies
import { CloudStateClient } from '@usecloudstate/react-core';
import { AuthProvider, config } from "@usecloudstate/react-web"

// 2. Initialize the client
const client = new CloudStateClient('solitary-bush-KOaZZPK0', config)

// 3. Add the AuthProvider inside your App component
function App(props) {
	return (
    <div className="todoapp stack-large">
	    <AuthProvider client={client} /> {/* This line is added */}
		</div>
	);
}

These are the App.js changes

image

4. Convert your useState to useCloudState

Now, whenever you want to save data to the cloud, you can convert that useState (which saves data locally) to useCloudState (which saves data globally throughout the app, and also to the cloud)

See this commit for the change

image

That's it!

Here's our completed project. We managed to completely sync the App state to the cloud in 7 lines of code.

Now when you go to your app, sign up, and do a state update, you should be able to see in in the Cloud State console. Feel free to check out the docs for more info.

image