Build the To-Do Client¶

邢晗日
2023-12-01

MongoDB Logo
ServerDriversCloudToolsGuides
Get MongoDB
Close ×
MongoDB Stitch

Introduction
Tutorials
    Overview
    Basic Blog Tutorial
        Blog App Overview
        Build the Blog Backend
        Build a Web-based Blog Client
    To-Do App Tutorial
        To-do App Overview
        Build the To-do Backend
        Build a To-do Client
        Add Google Authentication
        Add Facebook Authentication
        Add Collection-Level Watch
Users & Authentication
MongoDB Atlas
GraphQL
MongoDB Mobile
Functions
Triggers
External Services
Values & Secrets
Application Deployment
Hosting
Troubleshooting
Stitch Administration
Application Logs
Client SDKs
Release Notes

Stitch > Tutorials > To-Do App Tutorial 

Build the To-Do Client

Author: MongoDB Documentation Team

This tutorial walks you through building an app that uses Stitch for the backend, and enables users to create and maintain to-do lists.

Time required: 20 minutes
What You’ll Need

If you have not yet built the To-do backend, follow the steps in this guide.
Procedure

Now that you’ve set up a Stitch backend for your to-do application, you need a client application so that users can add, view, and complete to-do tasks. To help you get started, we’ve created client applications that include all the files and components you’ll need to follow this tutorial.

JavaScript Android (Java) iOS (Swift) GraphQL 

A. Get the Base To-Do Client Application

Estimated Time to Complete: ~10 minutes
1
Clone the Client App Repository

To get a local copy of the client application GitHub repository on your computer, clone the repo by running the following command in a terminal:

git clone https://github.com/mongodb-university/stitch-tutorial-todo-web.git

2
Install the App’s Dependencies

After you’ve cloned the repository to your computer, run the following code in your terminal to navigate into the repo and install the app’s dependencies:

cd stitch-tutorial-todo-web
npm install

Stitch Browser JS SDK

The base application that you cloned already lists the Stitch Browser SDK as a dependency so this step installs the SDK along with the other dependencies. For other applications, you can install the SDK from npm with the following command:

npm install --save mongodb-stitch-browser-sdk

3
Explore the Code and File Structure

The web client is a standard React web application scaffolded with create-react-app. We encourage you to explore the files in the app for a few minutes before you continue the tutorial. This will help you to familiarize yourself with what the app contains and where you’ll be working.

To-Do Client File Structure

src/
├── index.js
├── stitch/
│ ├── app.js
│ ├── mongodb.js
│ └── authentication.js
└── components/
├── App.js
├── Login.js
├── StitchAuth.js
├── Icon.js
├── TodoApp.js
├── TodoList.js
├── TodoControls.js
├── TodoInput.js
└── TodoItem.js

Stitch

The /src/stitch directory contains all of the code you’ll use to connect the application to Stitch. Each file in this directory exports functions and objects that encapsulate the Stitch component it’s named after. These files are only incomplete scaffolds. This tutorial walks through adding the missing code in these files to connect the app to Stitch.
React Components

The /src/components directory contains pre-built React components based on components from the reactstrap library and styled with Emotion. The components import code from the files in /src/stitch and use them to interact with Stitch. We’ve already completely implemented the React components so you won’t need to add any code to the component files.

React Components

React is a popular modern web application framework that uses a component model to maintain application state and intelligently render pieces of the UI. If you’re not familiar with React or want to brush up on your knowledge, check out the official React website which has excellent documentation and tutorials.
B. Integrate Your Stitch App

Estimated Time to Complete: ~10 minutes

Once you’re a little more familiar with the app’s file structure it’s time to get down to business and connect the app to Stitch. In this section you’ll be adding code to the following files in /src/stitch:

app.js
mongodb.js
authentication.js

After you complete this section the to-do client application will be connected to your Stitch backend and you’ll be able to add, complete, and hide to-do tasks through the app.
1
Connect to Stitch

The first thing that you need to do is connect the client application to your Stitch backend. In this step, you’ll instantiate an app client that provides objects and methods for interacting with Stitch. You need an app client to authenticate users, call Functions, and instantiate service clients.

To get started, navigate to the stitch-tutorial-todo-web repository and open the file /src/stitch/app.js. The file is incomplete and you will need to add some code to make the app work. The file should look like this when you first open it:
/src/stitch/app.js

1
2
3
4
5
6
7
8
9

import { Stitch } from “mongodb-stitch-browser-sdk”;

// TODO: Add your Stitch app’s App ID
const APP_ID = “”;

// TODO: Initialize the app client
const app =

export { app };

At the top of the file we import an object named Stitch from the Stitch Browser SDK. This object contains methods that instantiate and manage Stitch app clients. Each app client is associated with a single Stitch app that you specify by providing an App ID when you instantiate the client. At the bottom of the file we export the app object, which should contain an app client for your Stitch app.

There are two things you need to do to connect the to-do client to Stitch:

Replace <YOUR APP ID> with the App ID of your Stitch to-do app.

Find Your App ID

You can find your Stitch app’s App ID at the top of the left-hand navigation in the Stitch UI. Click the Copy button ( copy icon ) to copy it to your clipboard.
The App ID of a to-do app in the Stitch UI navigation

Instantiate an app client in the app variable by adding the following code:
	

7
8
9

	

const app = Stitch.hasAppClient(APP_ID)
  ? Stitch.getAppClient(APP_ID)
  : Stitch.initializeAppClient(APP_ID);

The Stitch object stores initialized app clients and throws an error if you attempt to initialize a second client with the same App ID, so we use a ternary expression and three methods on the Stitch object to create an app client. The ternary checks to see if an app client has already been inititialized and, if so, uses that instead of initializing a new app client.

Once you’ve added the code to app.js your client application is connected to Stitch! In the next steps you’ll use the app that you initialized and exported to actually interact with Stitch and MongoDB Atlas.
2
Instantiate a MongoDB Collection Handle

The To-do app stores to-do items in the MongoDB collection todo.items. You already defined rules for the collection in your Stitch app, so all you need to start running queries is a collection object that exposes MongoDB actions.

To get a handle for the todo.items collection, open the file /src/stitch/mongodb.js. The file should look like this when you first open it:
/src/stitch/mongodb.js

1
2
3
4
5
6
7
8
9
10

import { RemoteMongoClient } from “mongodb-stitch-browser-sdk”;
import { app } from “./app”;

// TODO: Initialize a MongoDB Service Client
const mongoClient =

// TODO: Instantiate a collection handle for todo.items
const items =

export { items };

At the top of the file we import a RemoteMongoClient object from the Stitch Browser SDK and the app that you defined and exported from app.js. The SDK will use the RemoteMongoClient to create a MongoDB service client that provides methods for interacting with your linked cluster. At the bottom of the file we export the items object, which should contain a collection handle that you can use to query the todo.items collection.

There are two things you need to do to create the collection handle:

Instantiate a MongoDB service client in the mongoClient variable by adding the following code:

5
6
7
8

const mongoClient = app.getServiceClient(
RemoteMongoClient.factory,
“mongodb-atlas”
);

MongoDB Service Name

The default cluster If you chose to name your linked MongoDB Atlas cluster something other than the default name, make sure to use that name when you get the service client.

Get the collection handle by adding the following code:

11

	

const items = mongoClient.db("todo").collection("items");

The app client provides a generic getServiceClient method that instantiates service clients for all Stitch services. To specify that the client is for a particular MongoDB service we provide a factory function from the RemoteMongoClient object and the name of the MongoDB service. The MongoDB service client that the method returns is similar to a MongoClient in a standard MongoDB driver. Given that, we can instantiate a collection handle by calling the db and collection methods.

How We Use It

In our React app, we use the collection handle that you instantiated to find, add, modify, and remove documents in the todo.items collection that represent a user’s to-do tasks. We write each query inside of a function that we return from the useTodoItems hook. Each function waits for its query to finish and then updates the React application state based on the query result by calling the dispatch function.
/src/components/useTodoItems.js

import { items } from “…/stitch”;

export function useTodoItems(userId) {
const [state, dispatch] = React.useReducer(todoReducer, { todos: [] });
const addTodo = async task => {
const todo = { task, owner_id: userId };
const result = await items.insertOne(todo);
dispatch({ type: “addTodo”, payload: { …todo, _id: result.insertedId } });
};
const removeTodo = async todoId => {
await items.deleteOne({ _id: todoId });
dispatch({ type: “removeTodo”, payload: { id: todoId } });
};
const completeAllTodos = async () => {
await items.updateMany({ owner_id: userId }, { $set: { checked: true } });
dispatch({ type: “completeAllTodos” });
};

// … more to-do action definitions
}

3
Set Up Anonymous User Login

Now that you’ve added the code to mongodb.js, your client application has a way to query MongoDB. However, Stitch requires that all requests be made by a user that has logged in through an authentication provider. Stitch allows you to configure one or more authentication providers that you can use to authenticate your app’s users and log them in. You already enabled Anonymous authentication in your Stitch app, so all that’s left to do is use the app.auth object to set up the authentication functions that the to-do client calls.

To set up anonymous authentication in your client app, open the file /src/stitch/authentication.js. The file should look like this when you first open it:
/src/stitch/authentication.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

import { AnonymousCredential } from “mongodb-stitch-browser-sdk”;
import { app } from “./app.js”;

export function loginAnonymous() {
// TODO: Allow users to log in anonymously
}

export function hasLoggedInUser() {
// TODO: Check if there is currently a logged in user
}

export function getCurrentUser() {
// TODO: Return the user object of the currently logged in user
}

export function logoutCurrentUser() {
// TODO: Logout the currently logged in user
}

At the top of the file we import an AnonymousCredential object from the Stitch Browser SDK and the app that you defined and exported from app.js. The AnonymousCredential is an object that we use to log in to Stitch as an anonymous user. The SDK also provides credential objects for each of the other authentication providers that Stitch supports, but you won’t need those for now. The file exports four incomplete functions that we use in our React components to handle user authentication.

To allow your users to log in and store to-do tasks in Stitch, you need to add code to make the exported authentication functions work.

The main thing you need to do is actually handle a user login request. To do so, add the following code to the loginAnonymous function:

4
5
6
7
8

export function loginAnonymous() {
// Allow users to log in anonymously
const credential = new AnonymousCredential();
return app.auth.loginWithCredential(credential);
}

You’ll also need to check if a user is currently logged in. Add the following code to the hasLoggedInUser function:

10
11
12
13

export function hasLoggedInUser() {
// Check if there is currently a logged in user
return app.auth.isLoggedIn;
}

If there is a logged in user, we want to be able to access their user object. Add the following code to the getCurrentUser function:

15
16
17
18

export function getCurrentUser() {
// Return the user object of the currently logged in user (if there is one)
return app.auth.isLoggedIn ? app.auth.user : null;
}

A logged in user should be able to log out of the to-do app. Add the following code to the logoutCurrentUser function:

20
21
22
23
24
25
26

export function logoutCurrentUser() {
// Logout the currently logged in user (if there is one)
const user = getCurrentUser();
if(user) {
return app.auth.logoutUserWithId(user.id);
}
}

How We Use It

In our React app, we use the authentication functions that you just completed to log users in and out, route logged out users to the login screen, and associate the logged in user’s id with their to-do tasks. We encapsulate this logic inside of a global app state that we modify using the handleAnonymousLogin and handleLogout functions. We expose the authentication state and functions to the app through React context in the StitchAuth component.
/src/components/StitchAuth.js

import {
hasLoggedInUser,
loginAnonymous,
logoutCurrentUser,
getCurrentUser
} from “./…/stitch/authentication”;

export function StitchAuthProvider(props) {
// Set up our authentication state and initialize it using the
// functions that we export from “/src/stitch/authentication.js”
const [authState, setAuthState] = React.useState({
isLoggedIn: hasLoggedInUser(),
currentUser: getCurrentUser()
});
const handleAnonymousLogin = async () => {
// Call the function we defined to log in to Stitch and then update
// our authentication state
if (!authState.isLoggedIn) {
const loggedInUser = await loginAnonymous();
setAuthState({
…authState,
isLoggedIn: true,
currentUser: loggedInUser
});
}
};
const handleLogout = async () => {
// Call the function we defined to log out of Stitch and then update
// our authentication state
if (authState.isLoggedIn) {
await logoutCurrentUser();
setAuthState({
…authState,
isLoggedIn: false,
currentUser: null
});
}
};
// In the actual code we call useMemo() on the value to improve performance
return (
<StitchAuthContext.Provider value={{
isLoggedIn: authState.isLoggedIn,
currentUser: authState.currentUser,
actions: { handleAnonymousLogin, handleLogout }
}}>
{props.children}
</StitchAuthContext.Provider>
);
}

4
Run the To-Do Client Application

Once you’ve added the code to authentication.js you should be able to log in and track to-do tasks. To run the app, navigate to the root of the stitch-tutorial-todo-web directory and run the following command:

npm start

The start command builds and serves a local copy of the application. Once the command output indicates that it is serving the app, open your browser to localhost:3000 to view the to-do client.

The app should show a login screen when you first start it. Click Log in Anonymously to log in as a new user and then add and check off some to-do tasks. If everything works, then you’ve successfully built the base to-do client!
Summary

Congratulations! You now have a working to-do app that lets users anonymously store, view, and complete to-do tasks.
What’s Next

This is the end of the base to-do client tutorial, but there’s still more that we can add. For example, if a user logs out they will not be able to log in with the same anonymous user account and thus will lose all of their saved to-do tasks. To solve this, we can implement a non-anonymous authentication method like email/password or OAuth 2.0 login for Facebook and Google. Look out for the next part of this tutorial, where we’ll integrate non-anonymous authentication into the to-do app.
← To-do App: Create a Stitch Backend Add Google OAuth to the To-Do Client →

© MongoDB, Inc 2008-present. MongoDB, Mongo, and the leaf logo are registered trademarks of MongoDB, Inc.
Was this page helpful?
Yes
No

 类似资料:

相关阅读

相关文章

相关问答