Search code examples
reactjstypescriptreact-hooksreact-admin

Data provider hooks in new react-admin version with nullable record context


In React-Admin the useRecordContext is now nullable. Before I could have a component that gets me the record and then fetches (or does something else with the data provider) something related to the record like this:

export const ExampleComponent= () => {
  const record = useRecordContext<User>();

  const { data } = useGetOne<Car>(`user/${record.userId}/cars/${record.carId}`, {});

  return <>{data.name}<>
}

However, since now the record can be undefined I can't do this anymore. According to the migration docs I should just check if record is undefined and return in such cases, however, this is not possible because of the rules of hooks. useGetOne can't be called conditionally:

React Hook "useGetOne" is called conditionally. React Hooks must be called in the exact same order in every component render. Did you accidentally call a React Hook after an early return?

How should such situations be handled? Handing over the record through props and only render the component when record is defined?


Solution

  • The useGetOne hook also consumes options, which are passed to the underlying useQuery hook. You can set the enabled option based on the availability of a defined record value. See Dependent Queries for complete details.

    Example Implementation:

    const record = useRecordContext<User>();
    
    const { data } = useGetOne<Car>(
      // Resource
      `user/${record.userId}/cars/${record.carId}`,
      // Meta
      {},
      // Options
      {
        enabled: !!record // <-- only enable when record is truthy
      }
    );