Created
November 29, 2021 06:35
-
-
Save kcsuraj/671174ed74916d77622e5cb01c198349 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { | |
ChangeEvent, | |
useState, | |
memo, | |
FC, | |
useCallback, | |
useMemo, | |
useRef, | |
useEffect, | |
} from "react"; | |
import "./App.css"; | |
import { v4 as uuidv4 } from "uuid"; | |
const getUsers = () => | |
Promise.resolve([ | |
{ | |
id: uuidv4(), | |
name: "Samita", | |
}, | |
]); | |
const App = () => { | |
const [query, setQuery] = useState<string>(""); | |
const [users, setUsers] = useState<Record<string, string>[]>([]); | |
const inputRef = useRef<HTMLInputElement | null>(null); | |
useEffect(() => { | |
getUsersFromApi(); | |
}, []); | |
useEffect(() => { | |
if (inputRef.current) { | |
inputRef.current.focus(); | |
} | |
}, []); | |
const getUsersFromApi = async () => { | |
const response = await getUsers(); | |
setUsers(response); | |
}; | |
const getUsersString = useMemo(() => { | |
console.log("getting users string"); | |
return users.map((user) => user.name).join(","); | |
}, [users]); | |
const handleInputChange = (e: ChangeEvent<HTMLInputElement>) => { | |
setQuery(e.target.value); | |
}; | |
const addUser = () => { | |
const newUsers = users.concat({ id: uuidv4(), name: query }); | |
setUsers(newUsers); | |
}; | |
const removeUser = useCallback((id: string) => { | |
const newUsers = users.filter((user) => user.id !== id); | |
setUsers(newUsers); | |
}, []); | |
return ( | |
<div> | |
<input | |
type="text" | |
value={query} | |
onChange={handleInputChange} | |
placeholder="Search" | |
ref={inputRef} | |
/> | |
<button onClick={() => addUser()}>Add user</button> | |
<Users users={users} onRemove={removeUser} /> | |
<br /> | |
{getUsersString} | |
</div> | |
); | |
}; | |
interface IUsers { | |
users: Record<string, string>[]; | |
onRemove: (id: string) => void; | |
} | |
const Users: FC<IUsers> = memo(({ users, onRemove }) => { | |
console.log("Users component"); | |
return ( | |
<div> | |
{users.map((user) => ( | |
<div key={user.id}> | |
{user.name} | |
<button onClick={() => onRemove(user.id)}>Remove</button> | |
</div> | |
))} | |
</div> | |
); | |
}); | |
export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment