Create a custom data provider in React-Admin
amit singh
2 min read
Let's start : )
First we have to create a file with a name of dataProvider.ts and import this to our App.tsx
App.tsx
import {
Admin,
defaultTheme,
Resource,
ListGuesser,
EditGuesser,
ShowGuesser,
Menu,
MenuItemLink,
Layout,
} from "react-admin";
import { authProvider } from "./authProvider";
import myDataProfider from './dataProvider';
export const App = () => (
<Admin authProvider={authProvider} dataProvider={myDataProfider} theme={myTheme}>
<Resource
name="blog"
list={PostList}
edit={PostEdit}
show={PostShow}
create={PostCreate}
options={{ "label": "blog", "menuParent": "blogs" }}
/>
</Admin>
);
dataProvider.ts
// dataProvider.ts
import { fetchUtils } from "react-admin";
import restServerProvider from 'ra-data-json-server';
// Add headers here
const httpClient = (url, options = {}) => {
if (!options.headers) {
options.headers = new Headers({ Accept: 'application/json' });
}
const token = localStorage.getItem('token');
options.headers.set('Authorization', `Bearer ${token}`);
return fetchUtils.fetchJson(url, options);
};
// Call rest provide function
const dataProvider = restServerProvider(servicesHost, httpClient);
// Types of provider in react-admin package.
/*
const dataProvider = {
getList: (resource, params) => Promise, // get a list of records based on sort, filter, and pagination
getOne: (resource, params) => Promise, // get a single record by id
getMany: (resource, params) => Promise, // get a list of records based on an array of ids
getManyReference: (resource, params) => Promise, // get the records referenced to another record, e.g. comments for a post
create: (resource, params) => Promise, // create a record
update: (resource, params) => Promise, // update a record based on a patch
updateMany: (resource, params) => Promise, // update a list of records based on an array of ids and a common patch
delete: (resource, params) => Promise, // delete a record by id
deleteMany: (resource, params) => Promise, // delete a list of records based on an array of ids
}
*/
const myDataProfider = {
...dataProvider,
create: async (resource, params) => {
// Select your resource to change request fields
if (resource == 'blog') {
formData.append('post_title', params.data.post_title);
formData.append('post_author', params.data.post_author);
formData.append('post_excerpt', params.data.post_excerpt);
formData.append('post_content', params.data.post_content);
formData.append('post_status', params.data.post_status);
formData.append('file', params.data.post_meta_thumbnail.rawFile);
return httpClient(`${servicesHost}/${resource}`, {
method: 'POST',
body: formData,
}).then(({ json }) => ({
data: { ...params.data, id: json.id },
}));
}
}
}
1
Subscribe to my newsletter
Read articles from amit singh directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by