Integrate Appwrite Storage API with React
Tags: react, appwrite, storage
Published: 2021-10-31 05:21:14

In this blog tutorial we going to create a react web app using Appwrite storage API.

## Step 1: ▶️ Initialize Appwrite and Create a React project

I have used Digital ocean to host my Appwrite instance.(Feel free to explore other hosting options)

First create a droplet in digital ocean (min. 2GB RAM / 2vCPU),
![Digital Ocean](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6ma98obtapo5j2anz170.png)
To install appwrite execute the following command (make sure you have docker installed in the instance),

```bash
docker run -it --rm \
    --volume /var/run/docker.sock:/var/run/docker.sock \
    --volume "$(pwd)"/appwrite:/usr/src/code/appwrite:rw \
    --entrypoint="install" \
    appwrite/appwrite:0.11.0
```
Use you IP address of your VM in browser to access your Appwrite console or you can add DNS "A record" pointing to your Droplet IP address and access the console using that domain.

![Appwrite Console](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nvawbo48tupjrhl8ctvz.png)

Now, create your React project using `create-react-app`
```bash
npx create-react-app appwrite-storage
```
And then install `appwrite` js package to your project.
```bash
npm install appwrite
```

## Step 2: 🔗 Connect you React App with Appwrite

Create a new project in Appwrite console.

Then, register a new web platform in Appwrite. For development purpose add `localhost` and for production register a new web platform with the domain name.

![Platform 1](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/e1dracp19ua8o20sl3mq.png)

![Platform 2](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tiynu0j47otyo3qe69n8.png)

For this project, I am going to use anonymous users instead of OAuth and email and password.

Now, use the api wrapper below 👇 to perform various operations with appwrite server. (You can also extend by adding various functions to it)

```js
// Create a new file under lib/appwrite.js
import { Appwrite } from "appwrite";

let api = {
  sdk: null,

  provider: () => {
    if (api.sdk) {
      return api.sdk;
    }
    let appwrite = new Appwrite();
    appwrite
      .setEndpoint("appwrite-endpoint-url")
      .setProject("project-id");
    api.sdk = appwrite;
    return appwrite;
  },

  createSession: (email, password) => {
    return api.provider().account.createAnonymousSession();
  },
  
  createFile: (file) => {
    return api.provider().storage.createFile(file, ["*"], ["*"]);
  },

  getFileView: (id) => {
    return api.provider().storage.getFileView(id);
  }
};

export default api;
```

You can find you `project-id` in appwrite console under settings in your project

![Project ID](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/53ea38aaq2ucu5cmrwch.png)

Yay 🥳 ! You have successfully connected your React App with Appwrite.

## Step 3: 👩‍💻 User Session management

> ***Warning: You cannot create a file in appwrite storage without signing in with a user***

For this project, I am going to use anonymous users (Feel free to explore other options too !)
You can explore other options [here](https://appwrite.io/docs/server/users) !

Now, create a anonymous user session when they land on your web app i.e. create new user under `src/App.js` using `useEffect` react hook.

```jsx
import "./index.css";
import { useEffect } from "react";
import api from "./lib/appwrite";

function App() {
  useEffect(() => {
    api
      .createSession()
      .then((response) => {
        console.log(response);
      })
      .catch((err) => console.log(err));
  }, []);

  return <div></div>;
}

export default App;
```
## Step 4: 📩 Create files in Appwrite Storage
We are going to use the helper function which we have created (`api.createFile()`) to upload file to Appwrite storage.

First we need a create a React form component with `input` field with type of `"file"`

```js
import "./index.css";
import { useEffect, useState } from "react";
import api from "./lib/appwrite";

function App() {
  useEffect(() => {
    api
      .createSession()
      .then((response) => {
        console.log(response);
      })
      .catch((err) => console.log(err));
  }, []);

  const [image, setImage] = useState(null);

  const handleSubmit = async () => {
    if (image !== null) {
      const respsone = await api.createFile(image);
      console.log(respsone);
    } else {
      alert("No file is uploaded");
    }
  };

  return (
    <div className="min-h-screen bg-primary flex justify-center items-center">
      <form onSubmit={() => handleSubmit()}>
        <input
          type="file"
          required
          onChange={(event) => setImage(event.currentTarget.file[0])}
        />
        <button type="submit">Submit</button>
      </form>
    </div>
  );
}

export default App;
```

## Step 5: 🔍 View file from Appwrite Storage

We are going to use the helper function which we have created (`api.getFileView()`) to get file URL from Appwrite storage.

To get the file URL you need a "File ID". There are two ways you can File ID. 

First one is you can get the ID from the response of the from `api.createFile()`,

```js
const respsone = await api.createFile(image);
console.log(respsone["$id"]); // Logs the file ID
```

The other is way is to get the File ID from the Appwrite console,

Navigate, to the file you want to get id for,
![ID](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ogssqfkoc3o4f1i4ry4o.png)

And get the file ID,
![ID](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/38uzjauz3quooian4hj8.png)

After getting the file ID, using the helper function mentioned above you get the file URL,

```js
const url = api.getFileView(fileId).href;
console.log(url);
```
Now, you can use this url to view the file you have stored in Appwrite Storage.

That's a wrap !✊. Now, you have successfully 🏆 built an React app with Appwrite Storage 🎉.