Manu
Manu

Reputation: 422

How to filter a list in react-admin with a parameter that is fetched asynchronously?

I am trying to filter a list in react-admin.

Basically, I have a list of classes, that I want to filter by teacherId. However, the teacherId has to be fetched asynchronously.

The code looks like this:

const activitiesFilters = [
  <TextInput key="search" source="q" label="Search an Activity" alwaysOn />,
]

export const ActivityList = (props) => {
  const teacher = useCurrentTeacherProfile() // This is the asynchronous call

  return (
    <List
      filters={activitiesFilters}
      filter={{ authorId: teacher?.id }} // Here I am using the teacher ID to filter my list
      {...props}
      exporter={false}
    >
      <Datagrid rowClick="edit">
        <TextField source="id" />
        <TextField source="title" />
        <TextField source="location" />
        <DateField source="dateTime" />
      </Datagrid>
    </List>
  )
}

The above code gives me this error:

Error: ActivityList suspended while rendering, but no fallback UI was specified. Add a <Suspense fallback=...> component higher in the tree to provide a loading indicator or placeholder to display.

I tried adding a <Suspense /> component above the <List /> but it doesn't work.

And if I add the <Suspense /> component at the root, above the <Admin /> one, it breaks the navigation.

Is there a way I can filter my list with a parameter that is fetched asynchronously?

Thanks!

Upvotes: 0

Views: 1548

Answers (1)

Ricola3D
Ricola3D

Reputation: 2442

I wonder if the error does not come from the "?." typescript operator in "teacher?.id" that resolves to undefined in JS before your async call resolves.

So I'd resolve the code as follow:

import { Loading } from 'react-admin';

const activitiesFilters = [
  <TextInput key="search" source="q" label="Search an Activity" alwaysOn />,
]

export const ActivityList = (props) => {
  const teacher = useCurrentTeacherProfile() // This is the asynchronous call

  if (!teacher) return <Loading/>

  return (
    <List
      filters={activitiesFilters}
      filter={{ authorId: teacher?.id }} // Here I am using the teacher ID to filter my list
      {...props}
      exporter={false}
    >
      <Datagrid rowClick="edit">
        <TextField source="id" />
        <TextField source="title" />
        <TextField source="location" />
        <DateField source="dateTime" />
      </Datagrid>
    </List>
  )
}

Upvotes: 1

Related Questions