Add database
In Appwrite, data is stored as a collection of documents. Create a new database and collection in the Appwrite Console to store the ideas.
Create a new collection with the following attributes:
Field | Type | Required | Size |
userId | String | Yes | 200 |
title | String | Yes | 200 |
description | String | No | 500 |
Change the collection's permissions in the settings to give access.
Navigate to the Settings tab of your collection, add the role Any and check the Read box. Next, add a Users role and give them access to Create, Update and Delete by checking those boxes.
Environment variables
Just like when we set up the connection to Appwrite in step 3, we need to keep the variables with the collection id secret. Open the .env file and add your database id and your collection id to it.
VITE_DATABASE_ID="YOUR_DATABASE_ID"
VITE_COLLECTION_ID="YOUR_COLLECTION_ID"
Query methods
Now that we have a collection in the database to hold ideas, we can connect to it from our app. Our users should be able to read, add and remove ideas. We will add a new composable, useIdeas, to handle this functionality.
Create a new file in the composables directory, useIdeas.js and add the following code.
// composables/useIdeas.ts
import { ID, Query, Models} from "appwrite";
import { database } from "~/appwrite";
import { ref } from "vue";
const ideasDatabaseId: string = import.meta.env.VITE_DATABASE_ID;
const ideasCollectionId: string = import.meta.env.VITE_COLLECTION_ID;
const queryLimit: number = 10;
interface Idea extends Models.Document{
title: string;
description: string;
userId: string;
}
const current = ref<Idea[] | null>(null); // Reference for the fetched data
export const useIdeas = () => {
// Fetch the 10 most recent ideas from the database
// Add the list to the current reference object
const fetch = async (): Promise<void> => {
const response = await database.listDocuments(
ideasDatabaseId,
ideasCollectionId,
[Query.orderDesc("$createdAt"), Query.limit(queryLimit)]
);
current.value = response.documents as Idea[];
};
// Add new idea to the database,
// Change the value of the current object
const add = async (idea: Idea): Promise<void> => {
const response = await database.createDocument(
ideasDatabaseId,
ideasCollectionId,
ID.unique(),
idea
);
current.value = [response, ...current.value as Idea[]].slice(0, 10) as Idea[];
};
const remove = async (id: string): Promise<void> => {
await database.deleteDocument(ideasDatabaseId, ideasCollectionId, id);
await fetch(); // Refetch ideas to ensure we have 10 items
};
fetch();
return {
add,
current,
fetch,
remove,
};
};
Now we can call the useIdeas composable from the home page.