reactjstypescripttsxappwrite

i am unable to save the user to into database collection of appwrite after creating the user?


i created the user with my signup form and it is successful created the account in the appwrite authentication but the I want to save the user into database collection as well :

api.ts

import { ID } from 'appwrite'
import { INewUser } from '@/types';
import { account, appwriteConfig, avatars, 
databases } from './config';

export async function createUserAccount(user: 
INewUser) {
try {
    const newAccount = await account.create(
        ID.unique(),
        user.email,
        user.password,
        user.name
    );
    if (!newAccount) {
        throw new Error("Failed to create 
    account");
    }

    const avatarUrl = 
    avatars.getInitials(user.name);
    const newUser = await saveUserToDB({
        accountId: newAccount.$id,
        name: newAccount.name,
        email: newAccount.email,
        username: user.username,
        imageUrl: avatarUrl,
    });

    if (!newUser) {
        throw new Error("Failed to save user to 
    database");
    }
    return newUser;

    } catch (error) {
    console.log(error);
    return error;
}
}


export async function saveUserToDB(user: {
accountId: string;
email: string;
name: string;
imageUrl: URL;
username?: string;
}) {
try {
    const newUser = await databases.createDocument(
        appwriteConfig.databaseId,
        appwriteConfig.userCollectionId,
        ID.unique(),
        user,
    );
    console.log(`the new user ${newUser}`);
    return newUser;
} catch (error) {
    console.log(error);
}
}

this ts file will create the user with the data coming from signup form

config.ts

import { Client, Account, Databases, Storage, 
Avatars } from 'appwrite'

export const appwriteConfig = {
projected: 
import.meta.env.VITE_APPWRITE_PROJECT_ID,
url: import.meta.env.VITE_APPWRITE_URL,
databaseId: 
import.meta.env.VITE_APPWRITE_DATABASE_ID,
storageId: 
import.meta.env.VITE_APPWRITE_STORAGE_ID,
userCollectionId: 
import.meta.env.VITE_APPWRITE_USERS_COLLECTION_ID,
postCollectionId: 
import.meta.env.VITE_APPWRITE_POSTS_COLLECTION_ID,
savesCollectionId: 
import.meta.env.VITE_APPWRITE_SAVES_COLLECTION_ID
}

export const client = new Client()
client.setProject(appwriteConfig.projectId);
client.setEndpoint(appwriteConfig.url);

export const account = new Account(client)
export const databases = new Databases(client)
export const storage = new Storage(client)
export const avatars = new Avatars(client)

index.ts for newUser which will define types

export type INewUser = {
name: string;
username: string;
email: string;
password: string;
};

SignupForm.tsx (button that will handle the signup request )

 <Button type="submit" className="shad- 
 button_primary">
        {isCreatingAccount || isSigningInUser || 
 isUserLoading ? (
          <div className="flex-center gap-2">
            <Loader /> Loading...
          </div>
        ) : (
          "Sign Up"
        )}
      </Button>

SignupForm.tsx ( main logic that will handle the request)

const SignupForm = () => {
const { toast } = useToast();
const navigate = useNavigate();
const { checkAuthUser, isLoading: isUserLoading } = 
useUserContext();

const form = useForm<z.infer<typeof 
SignupValidation>>({
resolver: zodResolver(SignupValidation),
defaultValues: {
  name: "",
  username: "",
  email: "",
  password: "",
},
});

 // Queries
 const { mutateAsync: createUserAccount, isPending: 
 isCreatingAccount } = useCreateUserAccount();
 const { mutateAsync: signInAccount, isPending: 
 isSigningInUser } = useSignInAccount();

 // Handler
 const handleSignup = async (user: z.infer<typeof 
 SignupValidation>) => {
  try {
  const newUser = await createUserAccount(user);

  if (!newUser) {
    toast({ title: "Sign up failed. Please try 
   again.", });

    return;
  }

  const session = await signInAccount({
    email: user.email,
    password: user.password,
  });

   if (!session) {
    toast({ title: "Something went wrong. Please 
   login your new account", });

     navigate("/sign-in");

    return;
   }

  const isLoggedIn = await checkAuthUser();

   if (isLoggedIn) {
    form.reset();

     navigate("/");
   } else {
     toast({ title: "Login failed. Please try 
  again.", });

    return;
  }
 } catch (error) {
  console.log({ error });
 }
 };

screenshot of the error i am getting Attribute not found in schema: accountId


Solution

  • I just had this exact same error, for me it was due to incorrect spelling.

    In your appwrite dashboard:

    Go to Collections > Users > Attributes

    Make sure that your attribute for accountId has been spelled exactly the same way as you have done so in your code.

    For me, I had accidentally created an attribute of acountId instead of accountId

    In order to change the spelling, you will need to delete your incorrectly spelled attribute and recreate a new accountId attribute

    Name: accountId, size: 2200, required: yes

    I hope this solves it for you