I am using react-query to fetch the users data to display via antd Table. The problem is that I am receiving 4 documents, while antd displays 3 in Table.
This is my code:
import React, { useEffect, useState, useContext } from 'react';
import { Table, notification, Popconfirm, Button, Spin, Input, Alert } from 'antd';
import { DeleteOutlined, EditOutlined, SearchOutlined } from '@ant-design/icons';
import Axios from 'axios';
import { SERVER_URL } from '../../config';
import { UserContext } from '../../App';
import { QueryClient, QueryClientProvider, useQuery } from 'react-query';
import { ReactQueryDevtools } from 'react-query/devtools';
import { Link, useHistory } from 'react-router-dom';
import * as _ from 'lodash';
import Highlighter from 'react-highlight-words';
const queryClient = new QueryClient();
let filterData = {
firstName: undefined,
lastName: undefined,
email: undefined,
page: 1,
pageSize: 10,
};
const UsersList = () => {
const history = useHistory();
const currentuser = useContext(UserContext);
const [filter, setFilter] = useState(filterData);
const [working, setWorking] = useState(false);
const [fetchTrigger, setFetchTrigger] = useState(false);
useEffect(() => {
filterData = { ...filterData, ..._.pickBy(_.get(history, 'location.state', null), _.identity) };
setFilter(filterData);
}, [history]);
// react query
async function fetchUsers(filter) {
const params = _.pickBy(filter, _.identity);
setWorking(true);
const { data } = await Axios.get(`${SERVER_URL}/users`, {
withCredentials: false,
headers: { Authorization: `Bearer ${currentuser.data.token}` },
params,
});
// setUsers(data);
setWorking(false);
console.log('DATA', data);
return data;
}
const { data, isError, isLoading } = useQuery({
queryKey: ['users-all', filter, fetchTrigger],
queryFn: () => fetchUsers(filter),
keepPreviousData: true,
});
const handleDelete = async (id) => {
try {
setWorking(true);
await Axios.delete(`${SERVER_URL}/users/${id}`, {
withCredentials: false,
headers: { Authorization: `Bearer ${currentuser.data.token}` },
});
setFetchTrigger(!fetchTrigger);
setWorking(false);
notification.success({
message: 'Success',
description: 'User deleted.',
placement: 'bottomRight',
});
} catch (error) {
setWorking(false);
console.log(error);
notification.error({
message: 'Error',
description: 'Problem with deleting user. Please try later.',
placement: 'bottomRight',
});
}
};
const columns = [
{
title: 'FIRST NAME',
dataIndex: ['firstName'],
key: 'firstName',
align: 'center',
// ...getColumnSearchProps(['firstName']),
},
{
title: 'LAST NAME',
dataIndex: ['lastName'],
key: 'lastName',
align: 'center',
// ...getColumnSearchProps(['lastName']),
},
{
title: 'EMAIL',
dataIndex: ['email'],
key: 'email',
align: 'center',
// ...getColumnSearchProps(['email']),
},
{
title: 'PREMIUM',
dataIndex: 'premium',
key: 'premium',
align: 'center',
render: (text, record) => (record.premium ? 'TRUE' : 'FALSE'),
// ...getColumnSearchProps(['premium']),
},
{
title: 'PHONE NUMBER',
dataIndex: 'phoneNumber',
key: 'phoneNumber',
align: 'right',
render: (text, record) => (record.phoneNumber ? record.phoneNumber : 'N/A'),
// ...getColumnSearchProps('name'),
},
{
title: 'CREATED AT',
dataIndex: 'createdAt',
key: 'createdAt',
align: 'right',
render: (text, record) => new Date(record.createdAt).toLocaleString('en-US'),
},
];
columns.push({
title: 'ACTION',
key: 'action',
align: 'center',
render: (text, record) => {
return (
<div
style={{
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
fontSize: '15px',
}}
>
<div style={{ margin: '2px', padding: '4px', cursor: 'pointer' }} className='table-actions'>
<EditOutlined onClick={() => history.push(`/admin/view-user/${record._id}`)} />
</div>
<div style={{ margin: '2px', padding: '4px', cursor: 'pointer' }} className='table-actions'>
<Popconfirm
title='Are you sure you want to delete this user?'
onConfirm={async () => handleDelete(record._id)}
onCancel={() => console.log('Cancel')}
okText='Yes'
cancelText='No'
>
<DeleteOutlined />
</Popconfirm>
</div>
</div>
);
},
});
const onChangeTable = (pagination, filters, sorter) => {
// eslint-disable-next-line array-callback-return
Object.keys(filters).map((prop) => {
filter[prop] = Array.isArray(filters[prop]) ? filters[prop][0] : filters[prop];
});
setFilter({ ...filter, ...{ page: pagination.current, pageSize: pagination.pageSize } });
};
//table usersWrapper
return (
<div className='content-wrapper'>
{isError && <Alert message={'Loading data problem...'} type='error' showIcon closable />}
<Spin spinning={working} tip='Loading...'>
<div className='actions-block' style={{ marginBottom: '8px' }}>
{/* <Input
bordered={false}
placeholder='Search'
prefix={<SearchOutlined />}
onChange={(e) => setSearch(e.target.value)}
/> */}
<Button onClick={() => console.log(1)} type='primary'>
Add user
</Button>
</div>
{data && data.length > 0 && (
<div className='table-user-okvir'>
<Table
size='middle'
onChange={onChangeTable}
bordered
columns={columns}
dataSource={[...data]}
rowKey={(record) => record._id}
// rowSelection={rowSelection}
pagination={{
pageSize: filter.pageSize || 10,
total: !isLoading ? data.length : 0,
current: filter.page || 1,
}}
/>
</div>
)}
</Spin>
</div>
);
};
export default function () {
return (
<QueryClientProvider client={queryClient}>
<ReactQueryDevtools initialIsOpen={false} />
<UsersList />
</QueryClientProvider>
);
}
// export default UsersList;
I tried to map and display the data via tag and it shows all 4. It seems the problem is with the Table itself. Any ideas?
I resolved it by adding scroll={{ y: 240 }}
which didn't actually add a scroll to my table but just expanded it a little bit and displayed the first row. Still have no idea why though xD...