-
-
Notifications
You must be signed in to change notification settings - Fork 5.3k
/
UPGRADE.md
2650 lines (2198 loc) · 91.1 KB
/
UPGRADE.md
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Upgrade to 4.0
## The Way To Define Custom Routes Has Changed
Custom routes used to be provided to the `Admin` component through the `customRoutes` prop. This was awkward to use as you had to provide an array of `<Route>` elements. Besides, we had to provide the `<RouteWithoutLayout>` component to support custom routes rendered without the `<Layout>` and keep TypeScript happy.
As we upgraded to react-router v6 (more on that later), we had to come up with another way to support custom routes.
Meet the `<CustomRoutes>` component. You you can pass it as a child of `<Admin>`, just like a `<Resource>`. It accepts react-router `<Route>` as its children (and only that). You can specify whether the custom routes it contains should be rendered with the `<Layout>` or not by setting the `noLayout` prop. It's `false` by default.
```diff
-import { Admin, Resource, RouteWithoutLayout } from 'react-admin';
+import { Admin, CustomRoutes, Resource } from 'react-admin';
const MyAdmin = () => (
<Admin
- customRoutes={[
- <Route path="/custom" component={MyCustomRoute} />,
- <RouteWithoutLayout path="/custom2" component={MyCustomRoute2} />,
- ]}
>
+ <CustomRoutes>
+ <Route path="/custom" element={<MyCustomRoute />} />
+ </CustomRoutes>
+ <CustomRoutes noLayout>
+ <Route path="/custom2" element={<MyCustomRoute2 />} />
+ </CustomRoutes>
<Resource name="posts" />
</Admin>
)
```
Note that `<CustomRoutes>` handles `null` elements and fragments correctly, so you can check for any condition before returning one of its children:
```jsx
const MyAdmin = () => {
const condition = useGetConditionFromSomewhere();
return (
<Admin>
<CustomRoutes>
<Route path="/custom" element={<MyCustomRoute />} />
{condition
? (
<>
<Route path="/a_path" element={<ARoute />} />
<Route path="/another_path" element={<AnotherRoute />} />
</>
)
: null}
</CustomRoutes>
</Admin>
);
}
```
## Admin Child Function Result Has Changed
In order to define the resources and their views according to users permissions, we used to support a function as a child of `<Admin>`. Just like the `customRoutes`, this function had to return an array of elements.
You can now return a fragment and this fragment may contains `null` elements. Besides, if you don't need to check the permissions for a resource, you may even include it as a direct child of `<Admin>`.
```diff
<Admin>
- {permissions => [
- <Resource name="posts" {...posts} />,
- <Resource name="comments" {...comments} />,
- permissions ? <Resource name="users" {...users} /> : null,
- <Resource name="tags" {...tags} />,
- ]}
+ <Resource name="posts" {...posts} />
+ <Resource name="comments" {...comments} />
+ <Resource name="tags" {...tags} />
+ {permissions => (
+ <>
+ {permissions ? <Resource name="users" {...users} /> : null}
+ </>
+ )}
</Admin>
```
Last thing, you can return any element supported by `<Admin>`, including the new `<CustomRoutes>`:
```jsx
import { Admin, Resource, CustomRoutes } from 'react-admin';
const MyAdmin = () => (
<Admin>
<Resource name="posts" {...posts} />
{permissions => (
<>
{permissions ? <Resource name="users" {...posts} /> : null}
<CustomRoutes>
{permissions ? <Route path="/a_path" element={<ARoute />} /> : null}
<Route path="/another_path" element={<AnotherRoute />} />
</CustomRoutes>
</>
)}
</Admin>
)
```
## React Router Upgraded to v6
This should be mostly transparent for you unless:
- you had custom routes: see [https://reactrouter.com/docs/en/v6/upgrading/v5#advantages-of-route-element](https://reactrouter.com/docs/en/v6/upgrading/v5#advantages-of-route-element) to upgrade.
- you used `useHistory` to navigate: see [https://reactrouter.com/docs/en/v6/upgrading/v5#use-usenavigate-instead-of-usehistory](https://reactrouter.com/docs/en/v6/upgrading/v5#use-usenavigate-instead-of-usehistory) to upgrade.
- you had custom components similar to our `TabbedForm` or `TabbedShowLayout` (declaring multiple sub routes): see [https://reactrouter.com/docs/en/v6/upgrading/v5](https://reactrouter.com/docs/en/v6/upgrading/v5) to upgrade.
## `useQuery`, `useMutation`, and `useQueryWithStore` Have Been Removed
React-admin v4 uses react-query rather than Redux for data fetching. The base react-query data fetching hooks (`useQuery`, `useMutation`, and `useQueryWithStore`) are no longer necessary as their functionality is provided by react-query.
If your application code uses these hooks, you have 2 ways to upgrade.
If you're using `useQuery` or `useMutation` to call a regular dataProvider method (like `useGetOne`), then you can use the specialized dataProvider hooks instead:
```diff
import * as React from "react";
-import { useQuery } from 'react-admin';
+import { useGetOne } from 'react-admin';
import { Loading, Error } from '../ui';
const UserProfile = ({ record }) => {
- const { loaded, error, data } = useQuery({
- type: 'getOne',
- resource: 'users',
- payload: { id: record.id }
- });
+ const { data, isLoading, error } = useGetOne(
+ 'users',
+ { id: record.id }
+ );
- if (!loaded) { return <Loading />; }
+ if (isLoading) { return <Loading />; }
if (error) { return <Error />; }
return <div>User {data.username}</div>;
};
```
If you're calling a custom dataProvider method, then you can use react-query's `useQuery`or `useMutation` instead:
```diff
-import { useMutation } from 'react-admin';
+import { useDataProvider } from 'react-admin';
+import { useMutation } from 'react-query';
const BanUserButton = ({ userId }) => {
- const { loaded, error, data } = useMutation({
- type: 'banUser',
- payload: userId
- });
+ const dataProvider = useDataProvider();
+ const { mutate, isLoading } = useMutation(
+ ['banUser', userId],
+ () => dataProvider.banUser(userId)
+ );
return <Button label="Ban" onClick={() => mutate()} disabled={isLoading} />;
};
```
Refer to [the react-query documentation](https://react-query.tanstack.com/overview) for more information.
## `<Query>` and `<Mutation>` Have Been Removed
The component version of `useQuery` and `useMutation` have been removed. Use the related hook in your components instead.
```diff
-import { Query } from 'react-admin';
+import { useGetOne } from 'react-admin';
const UserProfile = ({ record }) => {
- return (
- <Query type="getOne" resource="users" payload={{ id: record.id }}>
- {({ loaded, error, data }) => {
- if (!loaded) { return <Loading />; }
- if (error) { return <Error />; }
- return <div>User {data.username}</div>;
- }}
- </Query>
- );
+ const { data, isLoading, error } = useGetOne(
+ 'users',
+ { id: record.id }
+ );
+ if (isLoading) { return <Loading />; }
+ if (error) { return <Error />; }
+ return <div>User {data.username}</div>;
}
```
## `useDataProvider` No Longer Accepts Side Effects
`useDataProvider` returns a wrapper around the application `dataProvider` instance. In previous react-admin versions, the wrapper methods used to accept an `options` object, allowing to pass `onSuccess` and `onFailure` callbacks. This is no longer the case - the wrapper returns an object with the same method signatures as the original `dataProvider`.
If you need to call the `dataProvider` and apply side effects, use react-query's `useQuery` or `useMutation` hooks instead.
```diff
import { useDataProvider } from 'react-admin';
+import { useMutation } from 'react-query';
const BanUserButton = ({ userId }) => {
const dataProvider = useDataProvider();
+ const { mutate, isLoading } = useMutation();
const handleClick = () => {
- dataProvider.banUser(userId, { onSuccess: () => console.log('User banned') });
+ mutate(
+ ['banUser', userId],
+ () => dataProvider.banUser(userId),
+ { onSuccess: () => console.log('User banned') }
+ );
}
return <Button label="Ban" onClick={handleClick} disabled={isLoading} />;
};
```
Refer to [the react-query documentation](https://react-query.tanstack.com/overview) for more information.
## No More Records in Redux State
As Redux is no longer used for data fetching, the Redux state doesn't contain any data cached from the dataProvider anymore. If you relied on `useSelector` to get a record or a list of records, you now have to use the dataProvider hooks to get them.
```diff
-import { useSelector } from 'react-redux';
+import { useGetOne } from 'react-admin';
const BookAuthor = ({ record }) => {
- const author = useSelector(state =>
- state.admin.resources.users.data[record.authorId]
- );
+ const { data: author, isLoading, error } = useGetOne(
+ 'users',
+ { id: record.authorId }
+ );
+ if (isLoading) { return <Loading />; }
+ if (error) { return <Error />; }
return <div>Author {data.username}</div>;
};
```
## No More Data Actions
As Redux is no longer used for data fetching, react-admin doesn't dispatch Redux actions like `RA/CRUD_GET_ONE_SUCCESS` and `RA/FETCH_END`. If you relied on these actions for your custom reducers, you must now use react-query `onSuccess` callback or React's `useEffect` instead.
The following actions no longer exist:
- `RA/CRUD_GET_ONE`
- `RA/CRUD_GET_ONE_LOADING`
- `RA/CRUD_GET_ONE_FAILURE`
- `RA/CRUD_GET_ONE_SUCCESS`
- `RA/CRUD_GET_LIST`
- `RA/CRUD_GET_LIST_LOADING`
- `RA/CRUD_GET_LIST_FAILURE`
- `RA/CRUD_GET_LIST_SUCCESS`
- `RA/CRUD_GET_ALL`
- `RA/CRUD_GET_ALL_LOADING`
- `RA/CRUD_GET_ALL_FAILURE`
- `RA/CRUD_GET_ALL_SUCCESS`
- `RA/CRUD_GET_MANY`
- `RA/CRUD_GET_MANY_LOADING`
- `RA/CRUD_GET_MANY_FAILURE`
- `RA/CRUD_GET_MANY_SUCCESS`
- `RA/CRUD_GET_MANY_REFERENCE`
- `RA/CRUD_GET_MANY_REFERENCE_LOADING`
- `RA/CRUD_GET_MANY_REFERENCE_FAILURE`
- `RA/CRUD_GET_MANY_REFERENCE_SUCCESS`
- `RA/CRUD_CREATE`
- `RA/CRUD_CREATE_LOADING`
- `RA/CRUD_CREATE_FAILURE`
- `RA/CRUD_CREATE_SUCCESS`
- `RA/CRUD_UPDATE`
- `RA/CRUD_UPDATE_LOADING`
- `RA/CRUD_UPDATE_FAILURE`
- `RA/CRUD_UPDATE_SUCCESS`
- `RA/CRUD_UPDATE_MANY`
- `RA/CRUD_UPDATE_MANY_LOADING`
- `RA/CRUD_UPDATE_MANY_FAILURE`
- `RA/CRUD_UPDATE_MANY_SUCCESS`
- `RA/CRUD_DELETE`
- `RA/CRUD_DELETE_LOADING`
- `RA/CRUD_DELETE_FAILURE`
- `RA/CRUD_DELETE_SUCCESS`
- `RA/CRUD_DELETE_MANY`
- `RA/CRUD_DELETE_MANY_LOADING`
- `RA/CRUD_DELETE_MANY_FAILURE`
- `RA/CRUD_DELETE_MANY_SUCCESS`
- `RA/FETCH_START`
- `RA/FETCH_END`
- `RA/FETCH_ERROR`
- `RA/FETCH_CANCEL`
Other actions related to data fetching were also removed:
- `RA/REFRESH_VIEW`
- `RA/SET_AUTOMATIC_REFRESH`
- `RA/START_OPTIMISTIC_MODE`
- `RA/STOP_OPTIMISTIC_MODE`
## Changed Signature Of Data Provider Hooks
Specialized data provider hooks (like `useGetOne`, `useGetList`, `useGetMany` and `useUpdate`) have a new signature. There are 2 changes:
- `loading` is renamed to `isLoading`
- the hook signature now reflects the dataProvider signature (so every hook now takes 2 arguments, `resource` and `params`).
For queries:
```diff
// useGetOne
-const { data, loading } = useGetOne(
- 'posts',
- 123,
-);
+const { data, isLoading } = useGetOne(
+ 'posts',
+ { id: 123 }
+);
// useGetList
-const { data, ids, loading } = useGetList(
- 'posts',
- { page: 1, perPage: 10 },
- { field: 'published_at', order: 'DESC' },
-);
-return <>{ids.map(id => <span key={id}>{data[id].title}</span>)}</>;
+const { data, isLoading } = useGetList(
+ 'posts',
+ {
+ pagination: { page: 1, perPage: 10 },
+ sort: { field: 'published_at', order: 'DESC' },
+ }
+);
+return <>{data.map(record => <span key={record.id}>{record.title}</span>)}</>;
// useGetMany
-const { data, loading } = useGetMany(
- 'posts',
- [123, 456],
-);
+const { data, isLoading } = useGetMany(
+ 'posts',
+ { ids: [123, 456] }
+);
// useGetManyReference
-const { data, ids, loading } = useGetManyReference(
- 'comments',
- 'post_id',
- 123,
- { page: 1, perPage: 10 },
- { field: 'published_at', order: 'DESC' }
- 'posts'
-);
-return <>{ids.map(id => <span key={id}>{data[id].title}</span>)}</>;
+const { data, isLoading } = useGetManyReference(
+ 'comments',
+ {
+ target: 'post_id',
+ id: 123,
+ pagination: { page: 1, perPage: 10 },
+ sort: { field: 'published_at', order: 'DESC' }
+ }
+);
+return <>{data.map(record => <span key={record.id}>{record.title}</span>)}</>;
```
For mutations:
```diff
// useCreate
-const [create, { loading }] = useCreate(
- 'posts',
- { title: 'hello, world!' },
-);
-create(resource, data, options);
+const [create, { isLoading }] = useCreate(
+ 'posts',
+ { data: { title: 'hello, world!' } }
+);
+create(resource, { data }, options);
// useUpdate
-const [update, { loading }] = useUpdate(
- 'posts',
- 123,
- { likes: 12 },
- { id: 123, title: "hello, world", likes: 122 }
-);
-update(resource, id, data, previousData, options);
+const [update, { isLoading }] = useUpdate(
+ 'posts',
+ {
+ id: 123,
+ data: { likes: 12 },
+ previousData: { id: 123, title: "hello, world", likes: 122 }
+ }
+);
+update(resource, { id, data, previousData }, options);
// useUpdateMany
-const [updateMany, { loading }] = useUpdateMany(
- 'posts',
- [123, 456],
- { likes: 12 },
-);
-updateMany(resource, ids, data, options);
+const [updateMany, { isLoading }] = useUpdateMany(
+ 'posts',
+ {
+ ids: [123, 456],
+ data: { likes: 12 },
+ }
+);
+updateMany(resource, { ids, data }, options);
// useDelete
-const [deleteOne, { loading }] = useDelete(
- 'posts',
- 123,
- { id: 123, title: "hello, world", likes: 122 }
-);
-deleteOne(resource, id, previousData, options);
+const [deleteOne, { isLoading }] = useDelete(
+ 'posts',
+ {
+ id: 123,
+ previousData: { id: 123, title: "hello, world", likes: 122 }
+ }
+);
+deleteOne(resource, { id, previousData }, options);
// useDeleteMany
-const [deleteMany, { loading }] = useDeleteMany(
- 'posts',
- [123, 456],
-);
-deleteMany(resource, ids, options);
+const [deleteMany, { isLoading }] = useDeleteMany(
+ 'posts',
+ {
+ ids: [123, 456],
+ }
+);
+deleteMany(resource, { ids }, options);
```
This new signature should be easier to learn and use.
To upgrade, check every instance of your code of the following hooks:
- `useGetOne`
- `useGetList`
- `useGetMany`
- `useGetManyReference`
- `useCreate`
- `useUpdate`
- `useUpdateMany`
- `useDelete`
- `useDeleteMany`
And update the calls. If you're using TypeScript, your code won't compile until you properly upgrade the calls.
These hooks are now powered by react-query, so the state argument contains way more than just `isLoading` (`reset`, `status`, `refetch`, etc.). Check the [`useQuery`](https://react-query.tanstack.com/reference/useQuery) and the [`useMutation`](https://react-query.tanstack.com/reference/useMutation) documentation on the react-query website for more details.
## List `ids` Prop And `RecordMap` Type Are Gone
Contrary to `dataProvider.getList`, `useGetList` used to return data under the shape of a record map. This is no longer the case: `useGetList` returns an array of records.
So the `RecordMap` type is no longer necessary and was removed. TypeScript compilation will fail if you continue using it. You should update your code so that it works with an array of records instead.
```diff
-import { useGetList, RecordMap } from 'react-admin';
+import { useGetList, Record } from 'react-admin';
const PostListContainer = () => {
- const { data, ids, loading } = useGetList(
- 'posts',
- { page: 1, perPage: 10 },
- { field: 'published_at', order: 'DESC' },
- );
- return loading ? null: <PostListDetail data={data} ids={ids} />
+ const { data, isLoading } = useGetList(
+ 'posts',
+ {
+ pagination: { page: 1, perPage: 10 },
+ sort: { field: 'published_at', order: 'DESC' },
+ }
+ );
+ return isLoading ? null: <PostListDetail data={data} />
};
-const PostListDetail = ({ ids, data }: { ids: string[], data: RecordMap }) => {
+const PostListDetail = ({ data }: { data: Record[] }) => {
- return <>{ids.map(id => <span key={id}>{data[id].title}</span>)}</>;
+ return <>{data.map(record => <span key={record.id}>{record.title}</span>)}</>;
};
```
## Mutation Callbacks Can No Longer Be Used As Event Handlers
In 3.0, you could use a mutation callback in an event handler, e.g. a click handler on a button. This is no longer possible, so you'll have to call the callback manually inside a handler function:
```diff
const IncreaseLikeButton = ({ record }) => {
const diff = { likes: record.likes + 1 };
const [update, { isLoading, error }] = useUpdate('likes', { id: record.id, data: diff, previousData: record });
if (error) { return <p>ERROR</p>; }
- return <button disabled={isLoading} onClick={update}>Like</button>;
+ return <button disabled={isLoading} onClick={() => update()}>Like</button>;
};
```
TypeScript will complain if you don't.
To upgrade, check every instance of your code of the following hooks:
- `useCreate`
- `useUpdate`
- `useUpdateMany`
- `useDelete`
- `useDeleteMany`
Note that your code will be more readable if you pass the mutation parameters to the mutation callback instead of the mutation hook, e.g.
```diff
const IncreaseLikeButton = ({ record }) => {
const diff = { likes: record.likes + 1 };
- const [update, { isLoading, error }] = useUpdate('likes', { id: record.id, data: diff, previousData: record });
+ const [update, { isLoading, error }] = useUpdate();
+ const handleClick = () => {
+ update('likes', { id: record.id, data: diff, previousData: record });
+ };
if (error) { return <p>ERROR</p>; }
- return <button disabled={isLoading} onClick={update}>Like</button>;
+ return <button disabled={isLoading} onClick={handleClick}>Like</button>;
};
```
## `onSuccess` And `onFailure` Props Have Moved
If you need to override the success or failure side effects of a component, you now have to use the `queryOptions` (for query side effects) or `mutationOptions` (for mutation side effects).
For instance, here is how to override the side eggects for the `getOne` query in a `<Show>` component:
```diff
const PostShow = () => {
const onSuccess = () => {
// do something
};
const onFailure = () => {
// do something
};
return (
<Show
- onSuccess={onSuccess}
- onFailure={onFailure}
+ queryOptions={{
+ onSuccess: onSuccess,
+ onError: onFailure
+ }}
>
<SimpleShowLayout>
<TextField source="title" />
</SimpleShowLayout>
</Show>
);
};
```
Here is how to customize side effects on the `update` mutation in `<Edit>`:
```diff
const PostEdit = () => {
const onSuccess = () => {
// do something
};
const onFailure = () => {
// do something
};
return (
<Edit
- onSuccess={onSuccess}
- onFailure={onFailure}
+ mutationOptions={{
+ onSuccess: onSuccess,
+ onError: onFailure
+ }}
>
<SimpleForm>
<TextInput source="title" />
</SimpleForm>
</Show>
);
};
```
Here is how to customize side effects on the `create` mutation in `<Create>`:
```diff
const PostCreate = () => {
const onSuccess = () => {
// do something
};
const onFailure = () => {
// do something
};
return (
<Create
- onSuccess={onSuccess}
- onFailure={onFailure}
+ mutationOptions={{
+ onSuccess: onSuccess,
+ onError: onFailure
+ }}
>
<SimpleForm>
<TextInput source="title" />
</SimpleForm>
</Create>
);
};
```
Note that the `onFailure` prop was renamed to `onError` in the options, to match the react-query convention.
**Tip**: `<Edit>` also has a `queryOption` prop allowing you to specify custom success and error side effects for the `getOne` query.
The change concerns the following components:
- `useCreateController`
- `<Create>`
- `<CreateBase>`
- `useEditController`
- `<Edit>`
- `<EditBase>`
- `<SaveButton>`
- `useShowController`
- `<Show>`
- `<ShowBase>`
- `useDeleteWithUndoController`
- `useDeleteWithConfirmController`
- `<DeleteButton>`
- `<BulkDeleteButton>`
## `onSuccess` Callback On DataProvider Hooks And Components Has A New Signature
The `onSuccess` callback used to receive the *response* from the dataProvider. On specialized hooks, it now receives the `data` property of the response instead.
```diff
const [update] = useUpdate();
const handleClick = () => {
update(
'posts',
{ id: 123, data: { likes: 12 } },
{
- onSuccess: ({ data }) => {
+ onSuccess: (data) => {
// do something with data
}
}
);
};
```
The change concerns the following components:
- `useCreate`
- `useCreateController`
- `<Create>`
- `<CreateBase>`
- `useUpdate`
- `useEditController`
- `<Edit>`
- `<EditBase>`
- `<SaveButton>`
- `useGetOne`
- `useShowController`
- `<Show>`
- `<ShowBase>`
- `useDelete`
- `useDeleteWithUndoController`
- `useDeleteWithConfirmController`
- `<DeleteButton>`
- `useDeleteMany`
- `<BulkDeleteButton>`
## `<Edit successMessage>` Prop Was Removed
This prop has been deprecated for a long time. Replace it with a custom success handler in the `mutationOptions`:
```diff
-import { Edit, SimpleForm } from 'react-admin';
+import { Edit, SimpleForm, useNotify } from 'react-admin';
const PostEdit = () => {
+ const notify = useNotify();
+ const onSuccess = () => notify('Post updated successfully');
return (
- <Edit successMessage="Post updated successfully">
+ <Edit mutationOptions={{ onSuccess }}>
<SimpleForm>
...
</SimpleForm>
</Edit>
);
};
```
## The `useVersion` Hook Was Removed
React-admin v3 relied on a global `version` variable stored in the Redux state to force page refresh. This is no longer the case, as the refresh functionality is handled by react-query.
If you relied on `useVersion` to provide a component key, you can safely remove the call. The refresh button will force all components relying on a dataProvider query to re-execute.
```diff
-import { useVersion } from 'react-admin';
const MyComponent = () => {
- const version = useVersion();
return (
- <Card key={version}>
+ <Card>
...
</Card>
);
};
```
And if you relied on a `version` prop to be available in a page context, you can safely remove it.
```diff
import { useShowContext } from 'react-admin';
const PostDetail = () => {
- const { data, version } = useShowContext();
+ const { data } = useShowContext();
return (
- <Card key={version}>
+ <Card>
...
</Card>
);
}
```
## Application Cache No Longer Uses `validUntil`
React-admin's *application cache* used to reply on the dataProvider returning a `validUntil` property in the response. This is no longer the case, as the cache functionality is handled by react-query. Therefore, you can safely remove the `validUntil` property from your dataProvider response.
```diff
const dataProvider = {
getOne: (resource, { id }) => {
return fetch(`/api/${resource}/${id}`)
.then(r => r.json())
.then(data => {
- const validUntil = new Date();
- validUntil.setTime(validUntil.getTime() + 5 * 60 * 1000);
return {
data,
- validUntil
};
}));
}
};
```
This also implies that the `cacheDataProviderProxy` function was removed.
```diff
// in src/dataProvider.js
import simpleRestProvider from 'ra-data-simple-rest';
-import { cacheDataProviderProxy } from 'react-admin';
const dataProvider = simpleRestProvider('http://path.to.my.api/');
-export default cacheDataProviderProxy(dataProvider);
+export default dataProvider;
```
Instead, you must set up the cache duration at the react-query QueryClient level:
```jsx
import { QueryClient } from 'react-query';
import { Admin, Resource } from 'react-admin';
const App = () => {
const queryClient = new QueryClient({
defaultOptions: {
queries: {
staleTime: 5 * 60 * 1000, // 5 minutes
},
},
});
return (
<Admin dataProvider={dataProvider} queryClient={queryClient}>
<Resource name="posts" />
</Admin>
);
}
```
## No More Prop Injection In Page Components
Page components (`<List>`, `<Show>`, etc.) used to expect to receive props (route parameters, permissions, resource name). These components don't receive any props anymore by default. They use hooks to get the props they need from contexts or route state.
```diff
-const PostShow = (props) => (
+const PostShow = () => (
- <Show>
+ <Show {...props}>
<SimpleShowLayout>
<TextField source="title" />
</SimpleShowLayout>
</Show>
);
```
If you need to access the permissions previously passed as props, you need to call the `usePermissions` hook instead.
```diff
+const { usePermissions } from 'react-admin';
-const PostShow = ({ permissions, ...props }) => {
+const PostShow = () => {
+ const permissions = usePermissions();
return (
- <Show>
+ <Show {...props}>
<SimpleShowLayout>
<TextField source="title" />
{permissions === 'admin' &&
<NumberField source="nb_views" />
}
</SimpleShowLayout>
</Show>
);
};
```
If you need to access the `hasList` and other flags related to resource configuration, use the `useResourceConfiguration` hook instead.
```diff
+const { useResourceDefinition } from 'react-admin';
-const PostShow = ({ hasEdit, ...props }) => {
+const PostShow = () => {
+ const { hasEdit } = useResourceDefinition();
return (
<Show actions={hasEdit ? <ShowActions /> : null}>
<SimpleShowLayout>
<TextField source="title" />
</SimpleShowLayout>
</Show>
);
};
```
If you need to access a route parameter, use react-router's `useParams` hook instead.
```diff
+const { useParams } from 'react-router-dom';
-const PostShow = ({ id, ...props }) => {
+const PostShow = () => {
+ const { id } = useParams();
return (
<Show title={`Post #${id}`}>
<SimpleShowLayout>
<TextField source="title" />
</SimpleShowLayout>
</Show>
);
};
```
We used to inject a `syncWithLocation` prop set to `true` to the `<List>` components used in a `<Resource>`. This instructed the `<List>` to synchronize its parameters (such as pagination, sorting and filters) with the browser location.
As we removed the props injection, we enabled this synchronization by default for all `<List>`, used in a `<Resource>` or not. As a consequence, we also inverted this prop and renamed it `disableSyncWithLocation`. This doesn't change anything if you only used `<List>` components inside `<Resource list>`.
However, if you had multiple `<List>` components inside used a single page, or if you used `<List>` outside of a `<Resource>`, you now have to explicitly opt out the synchronization of the list parameters with the browser location:
```diff
const MyList = () => (
- <List>
+ <List disableSyncWithLocation>
// ...
</List>
)
```
## No More props injection in custom Pagination and Empty components
The `<List>` component renders a Pagination component when there are records to display, and an Empty component otherwise. You can customize these components by passing your own with the `pagination`and `empty`props.
`<List>` used to inject `ListContext` props (`data`, `isLoaded`, etc.) to these Pagination component. In v4, the component rendered by `<List>` no longer receive these props. They must grab them from the ListContext instead.
This means you'll have to do a few changes if you use a custom Pagination component in a List:
```diff
import { Button, Toolbar } from '@material-ui/core';
import ChevronLeft from '@material-ui/icons/ChevronLeft';
import ChevronRight from '@material-ui/icons/ChevronRight';
+import { useListContext } from 'react-admin';
-const PostPagination = (props) => {
+const PostPagination = () => {
- const { page, perPage, total, setPage } = props;
+ const { page, perPage, total, setPage } = useListContext();
const nbPages = Math.ceil(total / perPage) || 1;
return (
nbPages > 1 &&
<Toolbar>
{page > 1 &&
<Button color="primary" key="prev" onClick={() => setPage(page - 1)}>
<ChevronLeft />
Prev
</Button>
}
{page !== nbPages &&
<Button color="primary" key="next" onClick={() => setPage(page + 1)}>
Next
<ChevronRight />
</Button>
}
</Toolbar>
);
}
export const PostList = () => (
<List pagination={<PostPagination />}>
...
</List>
);
```
## `useListContext` No Longer Returns An `ids` Prop
The `ListContext` used to return two props for the list data: `data` and `ids`. To render the list data, you had to iterate over the `ids`.
Starting with react-admin v4, `useListContext` only returns a `data` prop, and it is now an array. This means you have to update all your code that relies on `ids` from a `ListContext`. Here is an example for a custom list iterator using cards:
```diff
import * as React from 'react';
import { useListContext, List, TextField, DateField, ReferenceField, EditButton } from 'react-admin';
import { Card, CardActions, CardContent, CardHeader, Avatar } from '@material-ui/core';
import PersonIcon from '@material-ui/icons/Person';
const CommentGrid = () => {
- const { data, ids, loading } = useListContext();
+ const { data, isLoading } = useListContext();
- if (loading) return null;
+ if (isLoading) return null;
return (
<div style={{ margin: '1em' }}>
- {ids.map(id =>
+ {data.map(record =>
- <Card key={id} style={cardStyle}>
+ <Card key={record.id} style={cardStyle}>
<CardHeader
- title={<TextField record={data[id]} source="author.name" />}
+ title={<TextField record={record} source="author.name" />}
- subheader={<DateField record={data[id]} source="created_at" />}
+ subheader={<DateField record={record} source="created_at" />}
avatar={<Avatar icon={<PersonIcon />} />}
/>
<CardContent>
- <TextField record={data[id]} source="body" />
+ <TextField record={record} source="body" />
</CardContent>
<CardActions style={{ textAlign: 'right' }}>
- <EditButton resource="posts" record={data[id]} />
+ <EditButton resource="posts" record={record} />
</CardActions>
</Card>
)}
</div>
);
};
```
## Removed Reducers
React-admin no longer relies on Redux to fetch relationships. Instead, the cache of previously fetched relationships is managed by react-query.
If you need to get the records related to the current one via a one-to-many relationship (e.g. to fetch all the books of a given author), you can use the `useGetManyReference` hook instead of the `oneToMany` reducer.
If you need to get possible values for a relationship, use the `useGetList` hook instead of the `possibleValues` reducer.
Besides, the `loadedOnce` reducer, used internally for the previous version of the List page logic, is no longer necessary and has been removed.
## Redux-Saga Was Removed
The use of sagas has been deprecated for a while. React-admin v4 doesn't support them anymore. That means that the Redux actions don't include meta parameters anymore to trigger sagas, the Redux store doesn't include the saga middleware, and the saga-based side effects were removed.
In particular, the data action creators (like `crudGetList`) don't support the `onSuccess` and `onFailure` callbacks anymore. You should use the related data provider hook (e.g. `useGetList`) instead.
If you still relied on sagas, you have to port your saga code to react `useEffect`, which is the standard way to write side effects in modern react.
## Removed Deprecated Elements