Basic config
Let's connect our Appwrite backend to our React frontend so we can begin interacting with real data from an actual database.
Setup ENV vars
To connect to our Appwrite backend, we'll need the following credentials. For safe keeping we'll add them into a .env
file in our projects root directory.
VITE_ENDPOINT=https://cloud.appwrite.io/v1
VITE_PROJECT_ID=
VITE_DATABASE_ID=
VITE_COLLECTION_NOTES_ID=
Connect SDK
Install appwrites web SDK: npm i appwrite
Create a config file in the following folder src/appwrite/config.js
import { Client, Databases } from "appwrite";
const client = new Client()
.setEndpoint(import.meta.env.VITE_ENDPOINT)
.setProject(import.meta.env.VITE_PROJECT_ID);
const databases = new Databases(client);
export { client, databases };
Database config
Instead of using the Appwrite web SDK directly, we'll wrap the build in methods given to us to allow more readable use of these built-in methods. I cover why we do this in a separate video which you can find here (opens in a new tab)
In our config file let's create an array for all future collections, which will hold the collection id, it's database id, and a human readable name such as "notes" which we can reference the collection by.
const collections = [
{
name: "notes",
id: import.meta.env.VITE_COLLECTION_NOTES_ID,
dbId: import.meta.env.VITE_DATABASE_ID
},
];
export { client, databases, collections};
Lets add the following code in it's own file: src/appwrite/databases.js
import { databases, collections } from "./config";
import { ID } from "appwrite";
const db = {};
collections.forEach((collection) => {
db[collection.name] = {
create: async (payload, id = ID.unique()) => {
return await databases.createDocument(
collection.dbId,
collection.id,
id,
payload
);
},
update: async (id, payload) => {
return await databases.updateDocument(
collection.dbId,
collection.id,
id,
payload
);
},
delete: async (id) => {
return await databases.deleteDocument(
collection.dbId,
collection.id,
id
);
},
get: async (id) => {
return await databases.getDocument(
collection.dbId,
collection.id,
id
);
},
list: async (queries) => {
return await databases.listDocuments(
collection.dbId,
collection.id,
queries
);
},
};
});
export { db };