React Todo Example App: Building a Full-Stack Application with User Authentication and Codehooks.io NoSQL backend
Tags: react, nosql, javascript, serverless
Published: 2023-06-12 20:29:25



In today's rapidly evolving web development landscape, full-stack development has become increasingly crucial. The ability to work seamlessly across both front-end and back-end technologies empowers developers to create comprehensive and robust applications. 

This writeup covers a React Todo example app as a full-stack application that includes a React frontend client, user authentication using [Auth0.com](https://auth0.com), and a  backend API with a NoSQL database using [codehooks.io](https://codehooks.io).

> Codehooks.io is an easy API and NoSQL service that lets developers build and deploy database backends and integrations insanely fast.

The Todo app allows users to create, update, and delete todo items. The user authentication is handled by Auth0, which provides a secure and easy-to-use authentication solution.

[You can read a detailed blog post for the Todo app development here](https://codehooks.io/blog/react-todo-example-app-with-secure-nosql-api-using-auth0.com).

[Check out a live example here](https://restdb.github.io/codehooks-io-react-todo/)

**The Todo app UI**

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9pyazewy7751d8t16cda.png)

**Authentication with Auth0.com**

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h91p259gluj2wmoo2gdg.png)

Here are a few code examples from the app:

## Setting up the app

```js
import { Auth0Provider } from "@auth0/auth0-react";

const domain = "YOUR_AUTH0_DOMAIN";
const clientId = "YOUR_AUTH0_CLIENT_ID";

ReactDOM.render(
  <Auth0Provider
    domain={domain}
    clientId={clientId}
    // Other configuration options
  >
    <App />
  </Auth0Provider>,
  document.getElementById("root")
);
```

## Backend API and database

```js
import { app, Datastore } from 'codehooks-js';

app.get('/todo', async (req, res) => {
  const db = await Datastore.open();
  // Fetch and return todo items from the database
const db = await Datastore.open();
  db.getMany('tododata', {
    filter: {owner: req.user.email}, // filter Todo items by authenticated user.email
    sort: {completed: 1, _id: -1}
  }).pipe(res);
});

app.post('/todo', async (req, res) => {
  const db = await Datastore.open();
  // Create a new todo item in the database
});

app.put('/todo/:id', async (req, res) => {
  const db = await Datastore.open();
  // Update a todo item in the database
});

app.delete('/todo/:id', async (req, res) => {
  const db = await Datastore.open();
  // Delete a todo item from the database
});

export default app.init();
```

## React frontend components

```js
import { useAuth0 } from "@auth0/auth0-react";

const TodoList = () => {
  const { isAuthenticated, loginWithRedirect } = useAuth0();

  if (!isAuthenticated) {
    return (
      <div>
        <p>Please log in to view your todos.</p>
        <button onClick={loginWithRedirect}>Log In</button>
      </div>
    );
  }

  // Render the todo list for authenticated users
};

export default TodoList;
```

## Calling the database API from the React frontend

```js
const callApi = async () => {
    try {      
      const token = await getAccessTokenSilently();
      const response = await fetch(`${apiOrigin}/todo`, {
        headers: {
          "Authorization": `Bearer ${token}`
        },
      });      
      let responseData = await response.json();
      console.log('Get data', responseData);
      responseData = responseData.map((todo) => {
        if (todo.completed === undefined) {
          todo.completed = false;
        }
        return todo;
      })      
      if (responseData) {
        setState({
          ...state, todoItems: responseData,
          error: null
        });
      }
    } catch (error) {
      console.error('API error', error)
      setState({
        ...state,
        error: error.error || error.message
      });
    }
  };
```

These examples demonstrate how the app integrates Auth0 for user authentication and uses the Codehooks.io backend to handle API requests and interact with the NoSQL database. The React components handle the user interface and logic for managing todo items.

Note: The code examples are simplified and may not include all necessary configurations and error handling. It's recommended to refer to the original source code and documentation for a complete understanding of the app's functionality.

* Full source code at [Github here](https://github.com/RestDB/codehooks-io-react-todo)
* Detailed [blog post here](https://codehooks.io/blog/react-todo-example-app-with-secure-nosql-api-using-auth0.com)

Happy coding! 💪