1
- import React , { useState , useReducer } from "react"
2
- import ReactDOM from "react-dom"
1
+ import React , { useState , useReducer , useCallback } from "react"
2
+ import { createRoot } from "react-dom/client "
3
3
4
4
const style = {
5
5
table : {
@@ -34,7 +34,7 @@ const style = {
34
34
} ,
35
35
}
36
36
37
- function PhoneBookForm ( { addEntryToPhoneBook } ) {
37
+ function PhoneBookForm ( { entries , setEntries } ) {
38
38
const initialFormState = {
39
39
userFirstname : "Coder" ,
40
40
userLastname : "Byte" ,
@@ -55,6 +55,24 @@ function PhoneBookForm({ addEntryToPhoneBook }) {
55
55
const onChange = ( { target : { name, value } } ) =>
56
56
dispatch ( { type : name , payload : value } )
57
57
58
+ const addEntryToPhoneBook = useCallback ( ( ) => {
59
+ const { userFirstname, userLastname, userPhone } = formState
60
+ const newEntries = [
61
+ ...entries ,
62
+ { userFirstname, userLastname, userPhone } ,
63
+ ]
64
+ const newSortedEntries = newEntries . sort ( ( a , b ) => {
65
+ const userLastnameA = a . userLastname . toLowerCase ( )
66
+ const userLastnameB = b . userLastname . toLowerCase ( )
67
+ return userLastnameA < userLastnameB
68
+ ? - 1
69
+ : userLastnameA > userLastnameB
70
+ ? 1
71
+ : 0
72
+ } )
73
+ setEntries ( newSortedEntries )
74
+ } , [ formState ] )
75
+
58
76
return (
59
77
< form
60
78
onSubmit = { e => {
@@ -132,34 +150,13 @@ function InformationTable({ entries }) {
132
150
133
151
function Application ( ) {
134
152
const [ entries , setEntries ] = useState ( [ ] )
135
-
136
- const addEntryToPhoneBook = ( {
137
- userFirstname,
138
- userLastname,
139
- userPhone,
140
- } ) => {
141
- const newEntries = [
142
- ...entries ,
143
- { userFirstname, userLastname, userPhone } ,
144
- ]
145
- const newSortedEntries = newEntries . sort ( ( a , b ) => {
146
- const userLastnameA = a . userLastname . toLowerCase ( )
147
- const userLastnameB = b . userLastname . toLowerCase ( )
148
- return userLastnameA < userLastnameB
149
- ? - 1
150
- : userLastnameA > userLastnameB
151
- ? 1
152
- : 0
153
- } )
154
- setEntries ( newSortedEntries )
155
- }
156
-
157
153
return (
158
154
< section >
159
- < PhoneBookForm addEntryToPhoneBook = { addEntryToPhoneBook } />
155
+ < PhoneBookForm entries = { entries } setEntries = { setEntries } />
160
156
< InformationTable entries = { entries } />
161
157
</ section >
162
158
)
163
159
}
164
160
165
- ReactDOM . render ( < Application /> , document . getElementById ( "root" ) )
161
+ const root = createRoot ( document . getElementById ( "root" ) )
162
+ root . render ( < Application /> )
0 commit comments