- Please see the code below, that I put some “console.log()”:
import axios, { CanceledError } from 'axios'
import { useEffect, useState } from 'react'
interface User {
id: number
name: string
}
function App() {
const [users, setUsers] = useState<User[]>([])
const [error, setError] = useState('')
const [loading, setLoading] = useState(false)
const deleteUser = (user: User) => {
const originalUsers = [...users]
setUsers(users.filter((u) => u.id !== user.id))
axios
.delete(`https://jsonplaceholder.typicode.com/users/${user.id}`)
.catch((err) => {
setError(err.message)
setUsers(originalUsers)
})
}
const addUser = () => {
const originalUser = [...users]
const newUser = { id: 0, name: 'Mosh' }
setUsers([newUser, ...users])
console.log('after calling 1st setUsers(), users =', users)
axios
.post('https://jsonplaceholder.typicode.com/users', newUser)
.then(({ data: savedUser }) => {
console.log('before calling 2nd setUsers(), users =', users)
setUsers([savedUser, ...users])
console.log('after calling 2nd setUsers(), users =', users)
})
.catch((err) => {
setError(err.message)
setUsers(originalUser)
})
}
useEffect(() => {
const controller = new AbortController()
setLoading(true)
axios
.get<User[]>('https://jsonplaceholder.typicode.com/users', {
signal: controller.signal,
})
.then((res) => {
setUsers(res.data)
setLoading(false)
})
.catch((err) => {
if (err instanceof CanceledError) return
setError(err.message)
setLoading(false)
})
return () => controller.abort()
}, [])
console.log('users =', users)
return (
<>
{error && <p className="text-danger">{error}</p>}
{loading && <div className="spinner-border"></div>}
<button className="btn btn-primary mb-3" onClick={addUser}>
Add
</button>
<ul className="list-group">
{users.map((user) => (
<li
key={user.id}
className="list-group-item d-flex justify-content-between"
>
{user.name}
<button
className="btn btn-outline-danger"
onClick={() => deleteUser(user)}
>
Delete
</button>
</li>
))}
</ul>
</>
)
}
export default App
- here’s the output of console.log() after clicking “Add Button” ONCE:
-
you see that the users data “after calling 1st setUsers()”, total = 11. means that “name: Mosh” is successfully added to users array and users array has 11 names.
-
see that the users data “before calling 2nd setUsers()”, users = 10. how come ? it supposed to be 11 right ?
Thank you