Front-end/React.js

react-admin 메모 : data provider

byolee 2020. 3. 2. 15:30

https://marmelab.com/react-admin/

 

React-admin - My First Project Tutorial

React-Admin Tutorial This 30 minutes tutorial will expose how to create a new admin app based on an existing REST API. Setting Up React-admin uses React. We’ll use Facebook’s create-react-app to create an empty React app, and install the react-admin packag

marmelab.com

 

설치

npm install react-admin

 


 

 

<ReferenceField> 컴포넌트는 혼자 display될 수 없음. reference data를 fetch 해서 child 컴포넌트에 전달해줌.

List 컴포넌트처럼 데이터를 fetching, preparing, delegate rendering함.

 

label 속성은 필드 레이블을 커스터마이징하기 위해 어떤 필드든지 사용할 수 있음.

 

 

 

- Data Providers (= Adapter for an API)

  • react-admin이 API와 통신할 때 마다 이 객체의 메소드를 호출함
  • 메소드 호출을 HTTP 리퀘스트로 바꿔주는 역할
  • HTTP response를 react-admin이 원하는 포맷으로 형식을 바꿈
  • <Admin> 컴포넌트의 prop으로 전달되기도 함
  • react-admin이 어떤 API와도 통신 가능하게 함
dataProvider
    .getOne('posts', { id: 123 })
    .then(response => {
        console.log(response.data); // { id: 123, title: "hello, world" }
    });
import { Admin, Resource } from 'react-admin';
import dataProvider from '../myDataProvider';

const App = () => (
    <Admin dataProvider={dataProvider}>
        // ...
    </Admin>
)

 

  • 반드시 아래와 같은 메소드를 가져야 함
const dataProvider = {
    getList:    (resource, params) => Promise,
    getOne:     (resource, params) => Promise,
    getMany:    (resource, params) => Promise,
    getManyReference: (resource, params) => Promise,
    create:     (resource, params) => Promise,
    update:     (resource, params) => Promise,
    updateMany: (resource, params) => Promise,
    delete:     (resource, params) => Promise,
    deleteMany: (resource, params) => Promise,
}

 

  • react-admin 버전2에서는 객체가 아니라 함수로서 사용되지만 버전3에 wrap하므로 사용 가능함

react-admin은 4개의 Data Provider를 포함한다.

Simple REST It serves mostly as an example. Incidentally, it is compatible with the FakeRest API.
JSON server Great for prototyping an admin over a yet-to-be-developed REST API.
Graphcool A provider for GraphQL servers following the Graphcool convention. Incidentally, this package builds up on marmelab/ra-data-graphql, which lets you develop providers for other GraphQL conventions.
Local JSON Based on a local object, it doesn’t even use HTTP. Use it for testing purposes.

 

 

 

Writing a Data Provider 

 

Method Usage Params format Response format
getList 리소스 서치 { pagination: { page: {int} , perPage: {int} }, sort: { field: {string}, order: {string} }, filter: {Object} } { data: {Record[]}, total: {int} }
getOne id로 1개 리소스 읽기 { id: {mixed} } { data: {Record} }
getMany id들로 리소스 배열 읽기 { id: {mixed[]} } { data: {Record[]} }
getManyReference 여러 레퍼런스로 리소스 배열 읽기 { target: {string}, id: {mixed}, pagination: { page: {int} , perPage: {int} }, sort: { field: {string}, order: {string} }, filter: {Object} } { data: {Record[]}, total: {int} }
create 싱글 리소스 생성 { data: {Object} } { data: {Record} }
update 싱글 리소스 업데이트 { id: {mixed}, data: {Object}, previousData: {Object} } { data: {Record} }
updateMany 여러 리소스 업데이트 { ids: {mixed[]}, data: {Object} } { data: {mixed[]} }
delete 하나 리소스 삭제 { id: {mixed}, previousData: {Object} } { data: {Record|null} } The record that has been deleted (optional)
deleteMany 여러 리소스 삭제 { ids: {mixed[]} } { data: {mixed[]} } The ids of the deleted records (optional)

 

 

error 

if (status < 200 || status >= 300) {
	return reject(
    	new HttpError(
            (json && json.message) || statusText,
             status,
             json
       	)
   );
}

 

usable hooks

 

  • useDataProvider
  • useQuery
  • useQueryWithStore
  • useMutation
  • useGetList
  • useGetOne
  • useGetMany
  • useGetManyReference
  • useCreate
  • useUpdate
  • useUpdateMany
  • useDelete
  • useDeleteMany
// 예시
import { useGetOne } from 'react-admin';

const UserProfile = ({ record }) => {
    const { data, loading, error } = useGetOne('users', record.id);
    if (loading) { return <Loading />; }
    if (error) { return <p>ERROR</p>; }
    return <div>User {data.username}</div>;
};