skip to Main Content

I have a request that displays users and their metadata to the console. How can I make it appear in a table on the website (in return())
This is my code:

const apiKey = process.env.CLERK_SECRET_KEY; // Получение значения apiKey из переменной окружения

if (!apiKey) {
  console.error('API_KEY не найден в переменных окружения');
  process.exit(1);
}

// Формируем заголовки запроса
const headers = {
  'Content-Type': 'application/json',
  'Authorization': `Bearer ${apiKey}`
};

// Отправляем GET-запрос для получения списка пользователей
axios.get('https://api.clerk.dev/v1/users', { headers })
  .then(response => {
    if (response.status === 200) {
      const users: Array<any> = response.data;

      // Перебираем пользователей и выводим first_name, last_name и метаданные
      users.forEach((user: any) => {
        const { first_name, last_name, public_metadata } = user;
        console.log(`First Name: ${first_name}, Last Name: ${last_name}`);

        // Проверяем, является ли public_metadata пустым
        if (public_metadata && Object.keys(public_metadata).length === 0) {
          // Присваиваем значение public_metadata
          user.public_metadata = { "role": 'user' };

          // Отправляем PATCH-запрос для обновления метаданных пользователя
          const userId = user.id;
          axios.patch(`https://api.clerk.dev/v1/users/${userId}/metadata`, {
            public_metadata: user.public_metadata
          }, { headers })
            .then(response => {
              if (response.status === 200) {
                console.log('Метаданные успешно обновлены');
              } else {
                console.log('Ошибка при обновлении метаданных');
              }
            })
            .catch(error => {
              console.log('Ошибка при выполнении запроса:', error.message);
            });
        }

        console.log('Metadata:', user.public_metadata.role);
      });
    } else {
      console.log('Ошибка при выполнении запроса');
    }
  })
  .catch(error => {
    console.log('Ошибка при выполнении запроса:', error.message);
  });

export default async function AdminDashboard(params: {
  searchParams: { search?: string };
}) {
  if (!checkRole("admin")) {
    redirect("/");
  }

  return (
    <>
      <h1></h1>
      <p>This page is restricted to users with the 'admin' role.</p>


    </>
  );
}

Columns: Name, user.role (public_metadata) and a separate column is empty

I want to see a table with all users on the site page

help me pls

2

Answers


  1. Chosen as BEST ANSWER

    no tabble I pasted your code and got some errors. Here they are

    i dont have tabble:(


  2. You are not using the axios request properly, below is how you can implement it.

    const apiKey = process.env.CLERK_SECRET_KEY;
    
    const getUsersData = async () => {
      if (!apiKey) return;
    
      const headers = {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${apiKey}`
      };
      const response = await axios.get('https://api.clerk.dev/v1/users', { headers })
      const users: Array<any> = response.data;
    
      users.forEach((user: any) => {
        const { first_name, last_name, public_metadata } = user;
        console.log(`First Name: ${first_name}, Last Name: ${last_name}`);
    
        if (public_metadata && Object.keys(public_metadata).length === 0) {
          user.public_metadata = { "role": 'user' };
    
          const userId = user.id;
          axios.patch(`https://api.clerk.dev/v1/users/${userId}/metadata`, {
                public_metadata: user.public_metadata
              }, { headers })
        }
      });
      return users;
    }
    
    export default async function AdminDashboard(params: {
      searchParams: { search?: string };
    }) {
      if (!checkRole("admin")) {
        redirect("/");
      }
    
      const usersData = await getUsersData()
    
      if (!usersData)
         return <div>No users</div>
    
      return (
        <>
          <h1></h1>
          <p>This page is restricted to users with the 'admin' role.</p>
          <UsersTable users={usersData} />
    
        </>
      );
    }
    
    // Implementation of table component, you can use some libraries also but this gives you more flexibility in styling, choose whatever you want
    
    export default function UsersTable({users}: {users: any[]}) {
      return <table>
        <tr>
          <th>Name</th>
          <th>Role</th>
        </tr>
        {users.map((user) => {
          return <tr>
                   <td>{user.name}</td>
                   <td>{user.role}</td>
                 </tr>
        })
      </table>
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search