-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsteps.txt
2513 lines (2098 loc) · 89.3 KB
/
steps.txt
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
17. FRONT-END SETUP
1. Setup
NOPE
npx create-react-app airbnb-react --template=typescript
npm i @chakra-ui/react @emotion/react @emotion/styled framer-motion
USE THIS INSTEAD
npx create-react-app my-app --template @chakra-ui/typescript
cd airbnb-react && code .
src > DELETE
only apptsx, indextsx, react-app-env left
index >
DEL import reportWebVitals from './reportWebVitals';
import './index.css';
reportWebVitals()
app >
DEL import logo from './logo.svg';
import './App.css';
return only <div/>
npm i react-router-dom
index >
surrond app with ChakraProvider
>npm run start
app >
<Text fontSize={"2xl"} color={"red.600"}>
hi
</Text>
2. Router Setup
Root acts as the base URL for website styles
Outlet allows a specific page to be rendered depending on the route
src > components.Root.tsx >
(rfce)
import { Outlet } from 'react-router-dom';
function Root() {
return (
<div>
Root
<Outlet />
</div>
)
}
export default Root
This is done in router.tsx, where a router variable referencing Root
as the element, and various routes as the children is created. But first,
some things need to change.
DELETE APP.tsx
index >
replace <App/> with <RouterProvider/>
replace import { App } from "./App"
with import { RouterProvider } from "react-router-dom"
Now create a routes folder and rfce 2 testing routes (Home.tsx & Users.tsx)
Then create the router.
src > router.tsx >
import { createBrowserRouter } from 'react-router-dom';
import Root from './components/Root';
const router = createBrowserRouter([{
path: "/",
element: <Root />,
children: [
{
path: "",
element: <Home />
},
{
path: "users",
element: <Users />
}
]
}]);
export default router;
Navigating to each route (http://localhost:3000/ & http://localhost:3000/users)
the text is different
3. Not Found page
DELETE USers.tsx
create NotFound.tsx in routes
add to router, before children variable and after path variable as errorElement
errorElement: <NotFound />,
navigate to non-existent page - works
NotFound
import { Button, Heading, Text, VStack } from '@chakra-ui/react'
import { Link } from 'react-router-dom';
function NotFound() {
return (
<VStack
justifyContent={"center"}
minH="100vh"
background={"gray.100"}
>
<Heading>Page not found.</Heading>
<Text>It seems you are lost</Text>
<Link to='/'>
<Button
variant={"link"}
// ghost, solid, link, outline
colorScheme={"twitter"}
// twitter, red
>Go home →</Button>
</Link>
</VStack>
);
}
export default NotFound
4. Chakra Tour
chakra-ui.com/docs/components
-------------------------------------------------------------------------
18. CHAKRA UI
1. Header
npm i react-icons
default theme chakra page
rem is based on the body font-size
if fs is 16px 1rem is 16px
icons are not chakra components, so need to be enclosed with a chakra box
to change color
Root.tsx>
import { Box, Button, HStack } from '@chakra-ui/react';
import { FaAirbnb } from 'react-icons/fa';
import { Outlet } from 'react-router-dom';
function Root() {
return (
<Box>
<HStack py={"5"} px={10} borderBottomWidth={1}
justifyContent="space-between">
<Box color={"red.500"}>
<FaAirbnb size={48} />
</Box>
<HStack spacing={"2rem"}>
<Button>Login</Button>
<Button colorScheme={"red"}>Signup</Button>
</HStack>
</HStack>
<Outlet />
</Box>
)
}
export default Root
2. Login Modal
<Modal isOpen={isOpen} onClose={onClose}>
<ModalOverlay />
<ModalContent>
<ModalHeader>Login</ModalHeader>
<ModalCloseButton />
<ModalBody>
<VStack>
<InputGroup>
<InputLeftElement children={
<Box color={"gray.500"}>
<FaUserNinja />
</Box>} />
<Input
placeholder='Username'
variant={"filled"} />
</InputGroup>
<InputGroup>
<InputLeftElement children={
<Box color={"gray.500"}>
<FaLock />
</Box>} />
<Input
placeholder='Password'
variant={"filled"} />
</InputGroup>
</VStack>
</ModalBody>
<ModalFooter>
<Button colorScheme={"red"} w={"100%"}>Login</Button>
</ModalFooter>
</ModalContent>
</Modal>
3. Signup Modal
Separate Compontents>
Header.tsx
SocialLogin.tsx
LoginModal.tsx
SignupModal.tsx
use useDisclosure to control each Modal
renaming isOpen, onOpen, onClose using :
eg. isOpen:isLoginOpen
4. Dark Mode
src>theme.ts
import { extendTheme, type ThemeConfig } from "@chakra-ui/react";
const config: ThemeConfig = {
initialColorMode: "light",
useSystemColorMode: false,
}
const theme = extendTheme({ config })
export default theme;
index.tsx > pass theme to ChakraProvider
import { ChakraProvider, ColorModeScript } from "@chakra-ui/react"
import theme from "./theme"
<ChakraProvider theme={theme}>
<ColorModeScript initialColorMode={theme.config.initialColorMode} />
...
ctrl + shift + j > application > local storage > delete key & restart server
updates based on theme.js theme (light, dark)
Header >
const { colorMode, toggleColorMode } = useColorMode();
<IconButton
onClick={toggleColorMode}
variant={"ghost"}
aria-label='Toggle Dark Mode'
icon={colorMode === "light" ? <FaMoon /> : <FaSun />} />
^ long way
> short way > [useColorModeValue(varforlight, varfordark)]
const colorToggleICon = useColorModeValue(<FaMoon />, <FaSun />)
...
icon={colorToggleICon} />
Wrap components in LightMode or DarkMode to force stylings for that Mode
regardless of current Mode
<LightMode>
<Button colorScheme={"red"}
onClick={onSignupOpen}
>Signup</Button>
</LightMode>
Animation >
Wrap component to animate (iconbutton) with AnimatorPresence & motion.div
with exitBeforeEnter & initial={false}
import { AnimatePresence, motion } from 'framer-motion';
<AnimatePresence exitBeforeEnter initial={false}>
<motion.div
style={{ display: 'inline-block' }}
key={useColorModeValue('light', 'dark')}
initial={{ y: -20, opacity: 0 }}
animate={{ y: 0, opacity: 1 }}
exit={{ y: 20, opacity: 0 }}
transition={{ duration: 0.1 }}
>
COMPONENT
</motion.div>
</AnimatePresence>
5. Rooms Grid
Home >
Create Grid component with boxes inside
<Grid
columnGap={4}
rowGap={8}
templateColumns={{
sm: "1fr",
md: "1fr 1fr",
lg: "repeat(3, 1fr)",
xl: "repeat(4, 1fr)",
"2xl": "repeat(4, 1fr)",
}}
px={{
sm: 10,
lg: 40,
}}
mt={10}
><Boxes......></Grid>
6. Responsive Design
templateColumns={{
sm: "1fr",
md: "1fr 1fr",
lg: "repeat(2, 1fr)",
xl: "repeat(3, 1fr)",
"2xl": "repeat(4, 1fr)",
}}
fix heading from hstack to stack to control direction depending on screen size>
<Stack py={5}
px={{
base: 10,
lg: 40,
}}
alignItems="center"
spacing={{
sm: 4,
md: 0,
}}
borderBottomWidth={1}
justifyContent={"space-between"}
direction={{
sm: "column",
md: "row",
}}>
Add custom breakpoints to theme.ts
const breakpoints = {
sm: '320px',
md: '768px',
lg: '960px',
xl: '1200px',
'2xl': '1536',
'3xl': '1800',
'4xl': '2266',
'5xl': '2655',
}
const theme = extendTheme({ config, breakpoints })
7. Skeletons
import { Box, HStack, Skeleton, SkeletonCircle, SkeletonText, Spacer } from "@chakra-ui/react"
function SkeletonRoom() {
return (
<Box>
<Skeleton height={{ sm: 315, lg: 290 }} rounded="3xl" mb={3} />
<HStack mb={-0.5} w={"100%"}>
<SkeletonText noOfLines={1} w={"70%"} />
<Spacer />
<SkeletonCircle py={1} px={7} />
</HStack>
<SkeletonText noOfLines={1} w={"50%"} mb={3} />
<SkeletonText noOfLines={1} w={"25%"} mt={4} />
</Box>
)
}
export default SkeletonRoom
_hover={{color:"red}}
-------------------------------------------------------------------------
19. REACT QUERY / TANSTACK QUERY
1. Manual Fetching
Trying
useEffect(() => {
fetch("http://127.0.0.1:8000/api/v1/rooms/");
}, [])
Will result in a CORS Error
if django-cors-headers not installed and configured
BACKEND
poetry add django-cors-headers
THIRD_PARTY_APPS = [... "corsheaders", ...]
MIDDLEWARE = [..., "corsheaders.middleware.CorsMiddleware",]
CORS_ALLOWED_ORIGINS = ["http://localhost:3000",]
NOT RECOMENDED FOR LARGER APPS
Testing isLoading with fetchRooms hook >
const [isLoading, setIsLoading] = useState(true);
const [rooms, setRooms] = useState();
const fetchRooms = async () => {
const res = await fetch("http://127.0.0.1:8000/api/v1/rooms/");
const json = await res.json();
setRooms(json);
setIsLoading(false);
}
useEffect(() => {
fetchRooms();
}, [])
...
{isLoading ? (
<>
<RoomSkeleton />
<RoomSkeleton />
</>
) : <Room />}
RECOMMENDED FOR LARGER APPS (REACT/TANSTACK QUERY) SEE 3
2. Recap
Room
interface IRoomProps {
name: string;
imageURL: string;
city: string;
country: string;
price: number;
rating: number;
}
function Room({ name, imageURL, rating, city, country, price }: IRoomProps) {
Home
interface IPhoto {
pk: string;
file: string;
description: string;
}
interface IRoom {
pk: number;
name: string;
city: string;
country: string;
price: number;
is_owner: boolean;
rating: number;
photos: IPhoto[];
}
function Home() {
const [isLoading, setIsLoading] = useState(true);
const [rooms, setRooms] = useState<IRoom[]>([]);
...
...
{rooms.map(room =>
<Room
key={room.pk}
name={room.name}
price={room.price}
rating={room.rating}
city={room.city}
country={room.country}
imageURL={
room.photos[0] == undefined ?
"https://a0.muscache.com/im/pictures/c2da931b-1f28-434c-8f99-d82f816a2ec6.jpg?im_w=720" :
room.photos[0].file == undefined ?
"data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAoHCBUWFRgVFRYYGBgYFRgSGBgYGBgYFRgYGBgZGRgYGBgcIS4lHB4rIRgYJjgmKy8xNTU1GiQ7QDs0Py40NTEBDAwMEA8QHhISHzQhJCc0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NP/AABEIALcBEwMBIgACEQEDEQH/xAAcAAABBQEBAQAAAAAAAAAAAAAFAAECAwQGBwj/xAA5EAABAwIEBAMGBQQCAwEAAAABAAIRAwQFEiExBkFRYRNxgRQiUpGhsTJCwdHhBxZi8HKSI0OCFf/EABoBAAIDAQEAAAAAAAAAAAAAAAABAgMEBQb/xAAnEQACAgICAQQCAgMAAAAAAAAAAQIRAyEEEjETMkFRFGEFIiOhwf/aAAwDAQACEQMRAD8A82tqQBV8BYG3BUnXBSpktD1qQKzmmFYapUC4o2LRAsT0olPCTaZUkJ+AgaohSw4gvkrPStyVO2blcroLdszZLcWkGMQYA1A2XBBRK5qlwhY22oUclOWiWGLjHZAXhWrPLFFlo1axbjLCraLgA9QCOewM6KbMOZ0USSAlIkEEI9RvK0CCdlbRw5k7I3RtWRstGF1ezHy4XVJMBi7rdSpuu6kbo4bViqfTYOitk1Xkx48ck/agXRqvO6y3gJ3RcvYFjuKjSqJO/k6GLHGO0qYD8ZwkKkMcTKIvaJTsDVBqy5a2gd4DidFqoioNFpa5o6KwVAiLcfBGcVL3KzM60e86lN/+Weq3MuW9QndeN6hN72wjGlSMIw8jmrrK3h8zyU33jeoVAvQDMpMki3GaGY78kFdaFFK14HcwszqwVaJ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dO+y5x9R9N+YSNefNKEb0RkerWj51T3LxJEarlMI4hDzrAIEAE80cdcBw35b+iWTHoUXss8QTCw49hwrUy3TMBmae6ta3n/vdWl4ykc0sNxYSpnmTaRBgjYwVqt7PMZjREsUpg1iBu7n3W2hawAFuyZKjZVGNsDutY5KLbbXVG6lvpAWXJlWGM5OWy5qkZwyBPIaIe5skolc1g0HuIQ+lstsVSKwxgzJ2KL+z/AOSEYXUA30Rdt234gt2JLqUTbsmLf/L6KD7f/L6KLb0dQpOvG8yFbSK7ZEWh1Ob6JxZH4vonZiLRzCZ2IN+IIpBb+hnWkfmUPZj8Ss9rZ8QVJu2/EEUh2yRt/wDIqJp/5fRN7UPiCg+6HUfRKkO2S8LuUlR7W34gkih7AAuH7hzv+xTi5fycfmU6SkVEfaH/ABu+ZTsvag/O7/sU6SAHfiVQ6Z3R0kqLcQqARmcP/op0kEhhf1OTnerirad7VH/sd8zCSSAIOqOOpJJ7ldHwnWyuOYk6aJJKuftJw9xbTuAb0zuB6TzR3Fm5gPmkkuZmSSNnyc9etDW67lcxiZ16n7J0lTDyDBUwdEcwfGiCGmegPXz9EklpSTWyB0hv9Pss/t5OhSSVdITBN0+K0yTt9UdYdAmSRm8II+SDnc/P9kPvq0AnlskkoYoqyUvBz9WuXu7LUwwITpLV8laHLtFHMnSW7H7SiXkfRRe5OkrCsiXaJAhJJFDtj+qiSmSQKyWbdRlJJILIpJJICz//2Q==" :
room.photos[0].file
}
3. React Query / Tanstack
Assists by not refetching already present data through caching
npm i @tanstack/react-query
index >
import {QueryClient, QueryClientProvider} from '@tanstack/react-query';
const client = new QueryClient();
root.render(
<React.StrictMode>
<QueryClientProvider client={client}>
<ChakraProvider theme={theme}>
<ColorModeScript initialColorMode={theme.config.initialColorMode} />
<RouterProvider router={router} />
</ChakraProvider>
</QueryClientProvider>
</React.StrictMode>,
)
api.ts >
const BASE_URL = "http://127.0.0.1:8000/api/v1"
export const getRooms = async () => {
const res = await fetch(`${BASE_URL}/rooms/`);
const json = await res.json();
return json;
}
Home >
DEL ALL CODE ABOVE RETURN AND BELOW Home
REPLACE WITH
const {isLoading, data} = useQuery<IRoom[]>(["rooms"], getRooms);
....
{data?.map(room =>
...
4. Axios
npm i axios
Adapter on top of fetch
api >
GUT
import axios from "axios";
const instance = axios.create({
baseURL: "http://127.0.0.1:8000/api/v1/",
});
export const getRooms = () => instance.get("rooms/").then(res => res.data);
5. Room Detail
Home >
add pk to room mapping
add pk to IRoom
Room >
add pk to IRoomProps and props for Room
routes > RoomDetail rfce
import { useParams } from "react-router-dom";
import { useQuery } from "@tanstack/react-query";
import { getRoomDetail } from "../api";
function RoomDetail() {
const { roomPk } = useParams();
const { isLoading, data } = useQuery([`room:${roomPk}`], getRoomDetail)
console.log(data);
return (
<div>RoomDetail</div>
)
}
export default RoomDetail
router >
children = [
...
{
path:"rooms/:roomPk",
element:<RoomDetail/>,
},
]
backend > roomdetaiserializer > get_is_liked:
if req.user.is_authenticated:
..code..
return False
6. Devtools and Query Keys
REPLACES CONSOLE.LOG at bottom of page (left corner)
npm i @tanstack/react-query-devtools
Add to Root below Outlet
import {ReactQueryDevtools} from '@tanstack/react-query-devtools';
...
<ReactQueryDevtools />
api >
import { QueryFunctionContext } from '@tanstack/react-query';
...
export const getRoomDetail = ({ queryKey }: QueryFunctionContext) => {
const [_, roomPk] = queryKey;
return instance.get(`rooms/${roomPk}`).then(res => res.data);
}
RoomDetail >
import { getRoomDetail } from "../api";
function RoomDetail() {
const { roomPk } = useParams();
const { isLoading, data } = useQuery([`room`, roomPk], getRoomDetail)
console.log(data);
return (
<div>RoomDetail</div>
)
}
7. Photos Grid
CREATE A TYPE DECLARATION FILE
src > types.d.ts
export interface IRoomPhotoPhoto {
pk: string;
file: string;
description: string;
}
export interface IRoomList {
pk: number;
name: string;
country: string;
city: string;
price: number;
rating: number;
is_owner: boolean;
photos: IRoomPhotoPhoto[];
}
export interface IRoomOwner {
name: string;
avatar: string;
username: string;
}
export interface IAmenity {
name: string;
description: string;
}
export interface IRoomDetail extends IRoomList {
created_at: string;
updated_at: string;
rooms: number;
toilets: number;
description: string;
address: string;
pet_friendly: true;
kind: string;
is_owner: boolean;
is_liked: boolean;
category: {
name: string;
kind: string;
};
owner: IRoomOwner;
amenities: IAmenity[];
}
DELETE Interfaces and
REPLACE IROOM with IROOMLIST and autoimport from above file
in Home.tsx >
...
const { isLoading, data } = useQuery<IRoomList[]>(["rooms"], getRooms);
...
GridItem instead of Box inside of Grid to customise columnSpan, rowSpan
Image objectFit={"cover"}
8. Reviews & Conclusion
types.d.ts >
export interface IReview {
payload: string;
rating: number;
user: IRoomOwner;
}
api >
export const getRoomReviews = ({ queryKey }: QueryFunctionContext) => {
const [_, roomPk] = queryKey;
return instance.get(`rooms/${roomPk}/reviews`).then(res => res.data);
}
RoomDetail >
...
<HStack mt={10} w={"40%"} justifyContent={"space-between"}>
<VStack alignItems={"flex-start"}>
<Skeleton isLoaded={!isLoading} h={"30px"}>
<Heading fontSize={'2xl'}>
House hosted by {data?.owner.username}
</Heading>
</Skeleton>
<Skeleton isLoaded={!isLoading} h={"30px"}>
<HStack justifyContent={"flex-start"} w={"100%"} >
<Text>{data?.toilets} toilet{data?.toilets == 1 ? "" : "s"}</Text>
<Text>|</Text>
<Text>{data?.rooms} room{data?.rooms == 1 ? "" : "s"}</Text>
</HStack>
</Skeleton>
</VStack>
<SkeletonCircle isLoaded={!isLoading} h="95px" w="95px">
<Avatar size={'xl'}
name={data?.owner.username}
src={data?.owner.profile_photo} />
</SkeletonCircle>
</HStack>
<Box mt={10}>
<Heading fontSize={'2xl'} mb={5}>
<Skeleton w={'40%'} isLoaded={!isLoading}>
<HStack>
<FaStar />
<Text>{data?.rating}</Text>
<Text fontSize={18}>|</Text>
<Text>{reviewsData?.length} review{reviewsData?.length === 1 ? "" : "s"}</Text>
</HStack>
</Skeleton>
</Heading>
<Container mx={"none"} maxW="container.lg" mt={35}>
<Grid templateColumns={"1fr 1fr"} gap={10}>
{reviewsData?.map((review, index) => (
<VStack key={index} alignItems={"flex-start"} spacing={0}>
<HStack >
<Avatar name={review.user.name}
src={review.user.profile_photo}
size={'md'}
/>
<VStack alignItems={"flex-start"}>
<Heading fontSize={'md'}>{review.user.username}</Heading>
<HStack spacing={1}>
<FaStar size={'12px'} />
<Text>{review.rating}</Text>
</HStack>
</VStack>
</HStack>
<Text>{review.payload}</Text>
</VStack>
))}
</Grid>
</Container>
</Box>
-------------------------------------------------------------------------
20. AUTHENTICATION (FRONTEND)
1. useUser
Make header aware of authentication status (login | sign up if out, avatar if in)
api >
export const getMe = () => instance.get(`users/me`).then((response) => response.data);
src.lib.useUser >
import { useQuery } from "@tanstack/react-query";
import { getMe } from "../api";
export default function useUser() {
const { isLoading, data, isError } = useQuery(["me"], getMe);
return {
userLoading: isLoading,
userData: data,
isLoggedIn: !isError,
}
}
tanstackquery will try multiple times on errors to get data before letting it fail
this will cause buttons below to not show for a few secs(even when not logged in)
This can be fixed by creating a config object in the usUser hook
FROM THIS :
const { isLoading, data, isError } = useQuery(["me"], getMe);
TO THIS:
const { isLoading, data, isError } = useQuery(["me"], getMe, {
retry: false,
});
Header >
{!userLoading ? (
!isLoggedIn ?
<>
<Button
onClick={onLoginOpen}
>
Login
</Button>
<LightMode>
<Button colorScheme={"red"}
onClick={onSignupOpen}
>
Signup
</Button>
</LightMode></> :
<Avatar size={'md'} />
) : null}
2. Credentials
Even if logged into Django admin panel, you will not be logged in on frontend
This is due to cookies not being sent from the correct origin
(localhost vs 127.0.0.1)
change to 127 in django
CORS_ALLOWED_ORIGINS = [
"http://127.0.0.1:3000",
]
also cookies are not sent by default by js, so we need to include them in
axios instance
api >
const instance = axios.create({
baseURL: "http://127.0.0.1:8000/api/v1/",
withCredentials: true,
});
however, django isnt prepared to receive these credentials, so we have to
enable it in settings >
CORS_ALLOW_CREDENTIALS = True
Header >
...
<Avatar name={userData?.username} size={'md'} src={userData?.profile_photo} />
) : null}
types >
export interface IUser {
last_login: string;
username: string;
email: string;
date_joined: string;
profile_photo: string;
name: string;
is_host: boolean;
gender: string;
language: string;
currency: string;
}
lib.useUser >
...
import { IUser } from "../types";
export default function useUser() {
const { isLoading, data, isError } = useQuery<IUser>(["me"], getMe, {
retry: false,
});
...
3. Log Out
Change Header Avatar section >
<Menu>
<MenuButton>
<Avatar name={userData?.username} size={'md'} src={userData?.profile_photo} />
</MenuButton>
<MenuList>
<MenuItem onClick={onLogOut}>Logout</MenuItem>
</MenuList>
</Menu>
api >
export const logOut = () => instance.post(`users/log-out`).then(res => res.data);
Add to Header >
...
const onLogOut = async () => {
const data = await logOut();
console.log(data);
}
...
Toasts
Header >
const toast = useToast();
const onLogOut = async () => {
const toastID = toast({
title: "Logging Out...",
description: "Goodbye :(",
status: "loading",
position: 'bottom-right'
// error, loading, info
// can also change color
});
// const data = await logOut();
// console.log(data);
setTimeout(() => {
toast.update(toastID, {
status: "success",
title: "Logged Out",
description: "Come back soon!",
duration: 2000
});
}, 5000)
}
4. CSRF
Django Settings >
CSRF_TRUSTED_ORIGINS = ["http://127.0.0.1:3000"]
Implement CSRF Token in headers of request (axios)
npm i js-cookie
npm i --save-dev @types/js-cookie
api >
import Cookie from 'js-cookie';
export const logOut = () => instance.post(`users/log-out`, null, {
headers: {
"X-CSRFToken": Cookie.get("csrftoken") || "",
}
}).then(res => res.data);
Works now,
Ensure prof pic updates with query client
Header >
const toast = useToast();
const queryClient = useQueryClient();
const onLogOut = async () => {
const toastID = toast({
title: "Logging Out...",
description: "Goodbye :(",
status: "loading",
position: 'bottom-right'
// error, loading, info
// can also change color
});
await logOut();
queryClient.refetchQueries(['me']);
setTimeout(() => {
toast.update(toastID, {
status: "success",
title: "Logged Out",
description: "Come back soon!",
duration: 2000
});
}, 500)
}
5. Github Login
OAuth
User >>> Github >>> Displayed with Requesting info, if accepted >>>
Our Website/confirm-gh?token=nj12i3bi >>>
Take Token >>> Django API >>> send GH token to Github API
>>> Receive information
https://github.com/settings/applications/new > CREATE
Note down Client ID & use in href of gh login with params of data u want
SocialLogin
<Button
href='https://github.com/login/oauth/authorize?client_id=0fbb1ad5fb0e65e0fbde&scope=read:user,user:email'
w={"100%"}
as="a"
leftIcon={<FaGithub />}
>
Continue with Github
</Button>
6. Github Code
routes > GithubConfirm.tsx >
import { Button, Heading, Spinner, Text, VStack } from '@chakra-ui/react'
import { useEffect } from 'react';
import { Link, useLocation } from 'react-router-dom';
import { githubLogin } from '../api';
export default function GithubConfirm() {
const { search } = useLocation();
const confirmLogin = async () => {
const params = new URLSearchParams(search);
const code = params.get("code");
if (code) {
await githubLogin(code);
}
}
useEffect(() => {
confirmLogin();
}, []);
return (
<VStack
justifyContent={"center"}
mt={40}
>
<Heading>Logging In...</Heading>
<Text>Please wait a moment.</Text>
<Spinner size={'lg'} />
</VStack>
);