DEV Community

Cover image for Integrate Appwrite Storage API with React
HarisaranG
HarisaranG

Posted on

Integrate Appwrite Storage API with React

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
To install appwrite execute the following command (make sure you have docker installed in the instance),

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
Enter fullscreen mode Exit fullscreen mode

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

Now, create your React project using create-react-app

npx create-react-app appwrite-storage
Enter fullscreen mode Exit fullscreen mode

And then install appwrite js package to your project.

npm install appwrite
Enter fullscreen mode Exit fullscreen mode

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

Platform 2

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)

// 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;
Enter fullscreen mode Exit fullscreen mode

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

Project ID

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 !

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.

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;
Enter fullscreen mode Exit fullscreen mode

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"

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;
Enter fullscreen mode Exit fullscreen mode

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(),

const respsone = await api.createFile(image);
console.log(respsone["$id"]); // Logs the file ID
Enter fullscreen mode Exit fullscreen mode

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

And get the file ID,
ID

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

const url = api.getFileView(fileId).href;
console.log(url);
Enter fullscreen mode Exit fullscreen mode

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 🎉.

Top comments (0)