Usa il componente Datagrid con query personalizzate - react-admin
Ricevi errori di seguito, quando utilizzi il componente Datagrid con query personalizzate. Il codice seguente funziona con react-admin ver 3.3.1, mentre non funziona con ver 3.8.1
TypeError: impossibile leggere la proprietà 'include' di undefined
Informazioni sulla console del browser: i componenti dell'elenco devono essere utilizzati all'interno di un <ListContext.Provider>. Fare affidamento su oggetti di scena piuttosto che sul contesto per ottenere dati e callback dell'elenco è deprecato e non sarà supportato nella prossima versione principale di react-admin.
Fare riferimento:https://marmelab.com/react-admin/List.html#Suggerimento: puoi utilizzare il componente Datagrid con query personalizzate:
import keyBy from 'lodash/keyBy'
import { useQuery, Datagrid, TextField, Pagination, Loading } from 'react-admin'
const CustomList = () => {
const [page, setPage] = useState(1);
const perPage = 50;
const { data, total, loading, error } = useQuery({
type: 'GET_LIST',
resource: 'posts',
payload: {
pagination: { page, perPage },
sort: { field: 'id', order: 'ASC' },
filter: {},
}
});
if (loading) {
return <Loading />
}
if (error) {
return <p>ERROR: {error}</p>
}
return (
<>
<Datagrid
data={keyBy(data, 'id')}
ids={data.map(({ id }) => id)}
currentSort={{ field: 'id', order: 'ASC' }}
basePath="/posts" // required only if you set use "rowClick"
rowClick="edit"
>
<TextField source="id" />
<TextField source="name" />
</Datagrid>
<Pagination
page={page}
perPage={perPage}
setPage={setPage}
total={total}
/>
</>
)
} ```
Please help!
Risposte
Dal momento che react-admin 3.7 <Datagrid>
e <Pagination>
leggi i dati da a ListContext
, invece di aspettarti che i dati vengano iniettati da oggetti di scena. <Datagrid>
Vedere ad esempio i documenti aggiornati suhttps://marmelab.com/react-admin/List.html#the-datagrid-component.
Il tuo codice funzionerà se lo avvolgi in un <ListContextProvider>
:
import React, { useState } from 'react';
import keyBy from 'lodash/keyBy'
import { useQuery, Datagrid, TextField, Pagination, Loading, ListContextProvider } from 'react-admin'
export const CustomList = () => {
const [page, setPage] = useState(1);
const perPage = 50;
const { data, total, loading, error } = useQuery({
type: 'GET_LIST',
resource: 'posts',
payload: {
pagination: { page, perPage },
sort: { field: 'id', order: 'ASC' },
filter: {},
}
});
if (loading) {
return <Loading />
}
if (error) {
return <p>ERROR: {error}</p>
}
return (
<ListContextProvider value={{
data: keyBy(data, 'id'),
ids: data.map(({ id }) => id),
total,
page,
perPage,
setPage,
currentSort: { field: 'id', order: 'ASC' },
basePath: "/posts",
resource: 'posts',
selectedIds: []
}}>
<Datagrid rowClick="edit">
<TextField source="id" />
<TextField source="name" />
</Datagrid>
<Pagination />
</ListContextProvider >
)
}