#[SOLVED] unable to delete user

1 messages · Page 1 of 1 (latest)

ionic apex
#

I'm trying to create a button in the user's profile(dashboard) page where a user can delete their account by themselves if they don't want to use the app.

But it's giving me this error.

Function for delete user:

const deleteUser = () => {
        const promise = account.delete();
        promise.then(
            function (response) {
                setUserDetails(response)
                console.log(response);
                router.push("/")
            },
            function (error) {
                console.log(error);
                window.location.reload()
            }
        )
    }

Button to make the action happen:

<div className="mt-10 py-10 border-t border-gray-300 text-center">
                            <div className="flex flex-col flex-wrap justify-center items-center">
                                <button className='flex flex-row gap-1 px-4 py-2 bg-red-600 hover:bg-red-800 text-white'
                                    onClick={() => {
                                        deleteUser(userDetails.$id)
                                    }}>
                                    <MdDeleteForever className='text-lg mt-1' /> Delete Account
                                </button>
                            </div>
                        </div>

Kindly help me with this issue

wide mauve
#

The Account SDK doesn't supports account deletion.
You'll need to use the users (Server) one.
https://appwrite.io/docs/server/users?sdk=nodejs-default#usersDelete

For example: inside a cloud-function

try{
  client
    .setEndpoint('https://cloud.appwrite.io/v1') 
    .setProject('5df5acd0d48c2')
    .setKey('919c2d18fb5d4...a2ae413da83346ad2');

  const userID = req.variables.APPWRITE_FUNCTION_EVENT_DATA ?? '';

  await users.delete(userID);
} catch (e) {
 // handle any error
}
ionic apex
#

I don't know how to write cloud function

wide mauve
#

Okay

#

Appwrite CLI
First install Appwrite CLI in case you've NPM is very easy just run

npm install -g appwrite-cli

Then login to your Appwrite using this command

appwrite login

You'll be prompt to enter username, password and your endpoint (https://cloud.appwrite.io/v1)

Function Creation
To create a function go to an empty project in your computer.
Attach the folder to existing project by using this command

appwrite init project

You'll be ask to choose the right project.

Now, we can create the function.

appwrite init function

You're gonna go over function creation wizard, Choose a name, ID and runtime.

Appwrite CLI will create a folder named function for you, within it you'll see all your functions.

#

Function code
For your use case you can write a function like this

const sdk = require("node-appwrite");

module.exports = async function (req, res) {
    const client = new sdk.Client();

    const users = new sdk.Users(client);

    if (
        !req.variables['APPWRITE_FUNCTION_ENDPOINT'] ||
        !req.variables['APPWRITE_FUNCTION_API_KEY']
    ) {
        console.warn("Environment variables are not set. Function cannot use Appwrite SDK.");
    } else {
        client
            .setEndpoint(req.variables['APPWRITE_FUNCTION_ENDPOINT'])
            .setProject(req.variables['APPWRITE_FUNCTION_PROJECT_ID'])
            .setKey(req.variables['APPWRITE_FUNCTION_API_KEY'])
            .setSelfSigned(true);
    }

    let success = false;

    try {
        const userID = req.variables.APPWRITE_FUNCTION_EVENT_DATA ?? '';

        await users.delete(userID);
        success = true;
    } catch (e) {

    }

    res.json({
        success,
    });
};

Function deploy
Now, You need to deploy your function to the cloud.
Run this

 appwrite deploy function

Go to your Appwrite cloud console and go into project -> function -> [Function name] -> settings
In the Update Variables section set these three variables.

APPWRITE_FUNCTION_ENDPOINT
APPWRITE_FUNCTION_PROJECT_ID
APPWRITE_FUNCTION_API_KEY

Go to you project -> overview -> Add Api key,
Give this key the user permissions (scope)

#

Running the function
The last step is to run the function.
So this could be your deleteUser function

const deleteUser = (id) => {
        const promise = functions.createExecution('[FUNCTION_ID]',id);
        promise.then(
            function (response) {
                setUserDetails(response)
                console.log(response);
                router.push("/")
            },
            function (error) {
                console.log(error);
                window.location.reload()
            }
        )
    }

Pass the user id to the deleteUser function then replace '[FUNCTION_ID]' with your new function ID.

#

That should cover all of your use-case and also can give you the advantage of using Appwrite cloud-function.

Appwrite Cloud-Function are actually pieces of puzzle your adding to you app backend.

ionic apex
#

let me try

ionic apex
wide mauve
ionic apex
#

Actually

#

I've made one in the cloud

#

Not sure if it's okay or not

wide mauve
#

You can create another one using the command line

ionic apex
#

It's showing me this while creating an api key

#

Which one to choose?

wide mauve
#

Select these two

ionic apex
#

ok

ionic apex
#

I have done account.get() to check for logged in user

#

But how to get their id?

#

<button className='flex flex-row gap-1 px-4 py-2 bg-red-600 hover:bg-red-800 text-white'
onClick={() => {
deleteUser(userDetails.$id)
}}>
<MdDeleteForever className='text-lg mt-1' /> Delete Account
</button>

#

Will this work?

wide mauve
#

Yes this should work

#

Or you can the current user id from the variable APPWRITE_FUNCTION_USER_ID

const sdk = require("node-appwrite");

module.exports = async function (req, res) {
    const client = new sdk.Client();

    const users = new sdk.Users(client);

    if (
        !req.variables['APPWRITE_FUNCTION_ENDPOINT'] ||
        !req.variables['APPWRITE_FUNCTION_API_KEY']
    ) {
        console.warn("Environment variables are not set. Function cannot use Appwrite SDK.");
    } else {
        client
            .setEndpoint(req.variables['APPWRITE_FUNCTION_ENDPOINT'])
            .setProject(req.variables['APPWRITE_FUNCTION_PROJECT_ID'])
            .setKey(req.variables['APPWRITE_FUNCTION_API_KEY'])
            .setSelfSigned(true);
    }

    let success = false;

    try {
        const userID = req.variables.APPWRITE_FUNCTION_USER_ID?? '';

        await users.delete(userID);
        success = true;
    } catch (e) {

    }

    res.json({
        success,
    });
};
ionic apex
#

@wide mauve not working

wide mauve
#

What is the error you're getting?

ionic apex
#

no error just when I'm clicking on the button the page is reloading and not redirecting

wide mauve
#

Nothing is being outputted to the console?
What you see in the network preview tab

ionic apex
#

After button click, while the page reloads it just showing undefined 2 times in the console

wide mauve
#

I think you didn't provided the $id for the deleteUser function at the end

wide mauve
#

But the function requires an ID to be sent to the function
Otherwise the function won't be able to know which user it need to delete

ionic apex
#

Same issue

#

Function code:

const sdk = require("node-appwrite");

module.exports = async function (req, res) {
  const client = new sdk.Client();

  const users = new sdk.Users(client);

  if (
    !req.variables['APPWRITE_FUNCTION_ENDPOINT'] ||
    !req.variables['APPWRITE_FUNCTION_API_KEY']
  ) {
    console.warn("Environment variables are not set. Function cannot use Appwrite SDK.");
  } else {
    client
      .setEndpoint(req.variables['APPWRITE_FUNCTION_ENDPOINT'])
      .setProject(req.variables['APPWRITE_FUNCTION_PROJECT_ID'])
      .setKey(req.variables['APPWRITE_FUNCTION_API_KEY'])
      .setSelfSigned(true);
  }

  let success = false;

  try {
    const userID = req.variables.APPWRITE_FUNCTION_USER_ID ?? '';

    await users.delete(userID);
    success = true;
  } catch (e) {

  }

  res.json({
    success,
  });
};
wide mauve
#

What is the result of the function?
You can find it in the preview tab (in the network tab)
Also you can check the function results in Appwrite console

ionic apex
#

How to check in console?

wide mauve
ionic apex
#

Hey wait

wide mauve
#

That means the function wasn't able to run

ionic apex
#

Seems like I have hit enter without selecting during deployment

#

let me try again

#

But still not working

wide mauve
#

Try to remove the reload then try again & check if you get any logs

  const deleteUser = (id) => {
    const promise = functions.createExecution('646b801508edd4a42aba', id);
    promise.then(
      function(response) {
        setUserDetails(response);
        console.log(response);
        router.push('/');
      },
      function(error) {
        console.log(error);
       // window.location.reload();
      }
    );
  };
ionic apex
#

Nothing's happening

#

Function is not getting executed on button click

wide mauve
#

Verify that id actually has the right value
Like so

 const deleteUser = (id) => {
    console.log(id);
    if(id === undefined){
      return;
    }
    const promise = functions.createExecution('646b801508edd4a42aba', id);
    promise.then(
      function (response) {
        setUserDetails(response);
        console.log(response);
        router.push('/');
      },
      function (error) {
        console.log(error);
        // window.location.reload();
      }
    );
  };
wide mauve
#

Good,
Just add permission for any User to execute the function

ionic apex
#

It worked

#

Thanks

#

Need another help on the same page

#

For this specific part:

const getCount = async (collection_id) => {
         const list = await databases.listDocuments("646605464de2f5cb7435", collection_id);
         const stats = `total is: ${list.total}`;
         return stats;
     }
#

Full code is above

wide mauve
#

What's the problem?

ionic apex
#

It was showing undefined

#

Actually the thing is the document is not getting created

#

For which it might be such thing

wide mauve
#

So this one works for you?

ionic apex
#

Document is also getting created

#

I'm now trying to get the total no of items in the collections of todolist

ionic apex
wide mauve
#

Okay, but getCount is async function
And you want it to return into the components?
I think for that you'll need to use other field in your state use it inside your HTML and update it in the getCount function

wide mauve
#

Yes