How can I access the react-admin store in the dataprovider? [React Admin 4.x]

Viewed 30

I'm trying to make use of a user-set variable in the react admin store when making API calls.

Specifically, I am storing a workspace ID in the store, which the user can set through a switcher. I want to be able to access this ID when making API calls, so that I can send over the workspace ID as a url parameter in the API request.

One soluion is to try to get the data directly from localstorage, but that seems hacky. Is there a btter way?

I'm using the latest version of react admin

2 Answers

In recent versions of React-admin, pass parameters like this:

"React-admin v4 introduced the meta option in dataProvider queries, letting you add extra parameters to any API call. Starting with react-admin v4.2, you can now specify a custom meta in <List>, <Show>, <Edit> and <Create> components, via the queryOptions and mutationOptions props."

https://marmelab.com/blog/2022/09/05/react-admin-septempter-2022-updates.html#set-query-code-classlanguage-textmetacode-in-page-components

import { Edit, SimpleForm } from 'react-admin'

const PostEdit = () => (
    <Edit mutationOptions={{ meta: { foo: 'bar' } }}>
        <SimpleForm>...</SimpleForm>
    </Edit>
)

@MaxAlex approach works well, but I went with a localStorage route, by setting a header in the fetchHTTP client defined with the dataprovider. This way I didn't have to modify each and every route.

const httpClient = (url: any, options: any) => {
  if (!options) {
    options = {};
  }
  if (!options.headers) {
    options.headers = new Headers({ Accept: 'application/json' });
  }

  const token = inMemoryJWT.getToken();
  const organization = localStorage.getItem('RaStore.organization');

  if (token) {
    options.headers.set('Authorization', `Bearer ${token}`);
  } else {
    inMemoryJWT.getRefreshedToken().then((gotFreshToken) => {
      if (gotFreshToken) {
        options.headers.set(
          'Authorization',
          `Bearer ${inMemoryJWT.getToken()}`,
        );
      }
    });
  }

  if (organization) {
    options.headers.set('Organization-ID', organization);
  }

  return fetchUtils.fetchJson(url, options);
};

I also looked into the react admin internals, and the store provider is one level below the dataprovider. This means there isn't an easy way to access the store without refactoring the entire Admin provider stack.

Related