import React, { useEffect, useState } from 'react'
import { useSelector, useDispatch } from 'react-redux'
import { selectAllPosts, fetchPosts, handleDelete } from './postsSlice'
import { UpdatePostForm } from './UpdatePostForm'
const PostExcerpt = ({ post }) => {
const [showEditForm, setShowEditForm] = useState(false);
const [updateId, setUpdateId] = useState('')
const dispatch = useDispatch()
const handleUpdate = (id) => {
setUpdateId(id);
setShowEditForm(true);
}
return (
<article key={post.id}>
<h3>{post.title}</h3>
<p>{post.content}</p>
{showEditForm && updateId === post.id ? (
<UpdatePostForm
post={post}
setShowEditForm={setShowEditForm}
/>
) : (
<button onClick={() => handleUpdate(post.id)}>
Update
</button>
)}
<button onClick={() => dispatch(handleDelete(post.id))}>Delete</button>
</article>
)
}
export const PostsList = () => {
const dispatch = useDispatch()
const posts = useSelector(selectAllPosts)
console.log(posts)
const status = useSelector(state => state.posts.status)
console.log(status)
const error = useSelector(state => state.posts.error)
console.log(error)
useEffect(() => {
status === 'idle' && dispatch(fetchPosts())
},[status, dispatch])
let content
status === 'loading' ? (
content = <h1>Loading...</h1>
) : status === 'succeeded' ? (
content = posts.map(post => <PostExcerpt key={post.id} post={post} />)
) : (
content = <div>Error: {error}</div>
)
return (
<section>
<h2>Posts</h2>
{content}
</section>
)
}
console.log("The PostsList.js rendered")
PostsList.js rendered three times:
Initial state:
PostsList.js:41 []
PostsList.js:44 idle
PostsList.js:47 null
The state after thunk fetchPosts dispeched action type pending:
PostsList.js:41 []
PostsList.js:44 loading
PostsList.js:47 null
The state after thunk fetchPosts dispeched action type fulfilled:
PostsList.js:41 (2) [{…}, {…}]
PostsList.js:44 succeeded
PostsList.js:47 null
PostsSlice.js is created initial state:
const initialState = {
posts: [],
status: 'idle',
error: null,
};
and the initial state of PostsList.js was the same.
More: https://www.youtube.com/watch?v=eSbvt0qm2lw&list=PLvYzjHQxr_s3RucuEWrkdhGcgdvYEjOA5
GitHub: https://github.com/ivicakartelo/thunk1
Do this for your homework:
- Explain the reason for all three renderings.
Primjedbe
Objavi komentar