Search code examples
javascriptreactjsag-gridgraphql-jsag-grid-react

Query results into an AG-Grid


I want to display all the users and email into an ag-grid but nothing I do seems to Work. I am using react JavaScript in order to build an admin portal.

import React from 'react';
import './users.css'
import { useQuery, gql } from '@apollo/client';
import { AgGridReact } from 'ag-grid-react';
import 'ag-grid-community/dist/styles/ag-grid.css';
import 'ag-grid-community/dist/styles/ag-theme-alpine.css';
const USER_QUERY = gql`
{
    users {
      _id
        username
        email
    }
}
`;

export default function Users() {
  const { data, loading, error } = useQuery(USER_QUERY);

  if (loading) return <p>loading...</p>;
  if (error) return <p>ERROR</p>;
  if (!data) return <p>Not found</p>;

  const [columnDefs] =[
    { field: "username" },
    { field: "email" },
  ];


  const [rowData] = data.users.map(user => {
    return (
      {
        username: user.username,
        email: user.email,
      }
    )
  }
  );

  return (
    <div className="ag-theme-alpine" style={{ height: 400, width: 600 }}>
      <AgGridReact
        rowData={rowData}
        columnDefs={columnDefs}>
      </AgGridReact>
    </div>
  );
};

Any pointers on what I am doing wrong? or any fixes for this.


Solution

  • Removing [ ] from

    const [columnDefs] =[
        { field: "username" },
        { field: "email" },
      ];
    
    const ]rowData] = data.users.map(user => {
        return (
          {
            username: user.username,
            email: user.email,
          }
        )
      }
      );
    

    to

     const columnDefs =[
        { field: "username" },
        { field: "email" },
      ];
    
    
      const rowData = data.users.map(user => {
        return (
          {
            username: user.username,
            email: user.email,
          }
        )
      }
      );