Skip to content

Commit

Permalink
Convert posts to useReducer
Browse files Browse the repository at this point in the history
  • Loading branch information
gusaiani committed Dec 4, 2019
1 parent c1dd42d commit dc13c51
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 5 deletions.
15 changes: 13 additions & 2 deletions src/App.js
Expand Up @@ -28,15 +28,26 @@ function userReducer (state, action) {
}
}

function postsReducer (state, action) {
const {title, content, author} = action
switch (action.type) {
case 'CREATE_POST':
const newPost = {title, content, author}
return [ newPost, ...state ]
default:
throw new Error()
}
}

export default function App () {
const [ user, dispatchUser ] = useReducer(userReducer, '')
const [ posts, setPosts ] = useState(defaultPosts)
const [ posts, dispatchPosts ] = useReducer(postsReducer, defaultPosts)

return (
<div style={{ padding: 8 }}>
<UserBar user={user} dispatch={dispatchUser} />
<br />
{user && <CreatePost user={user} posts={posts} setPosts={setPosts} />}
{user && <CreatePost user={user} posts={posts} dispatch={dispatchPosts} />}
<br />
<hr />
<PostList posts={posts} />
Expand Down
5 changes: 2 additions & 3 deletions src/post/CreatePost.js
@@ -1,6 +1,6 @@
import React, { useState } from 'react'

export default function CreatePost ({ user, posts, setPosts }) {
export default function CreatePost ({ user, posts, dispatch }) {
const [ title, setTitle ] = useState('')
const [ content, setContent ] = useState('')

Expand All @@ -15,8 +15,7 @@ export default function CreatePost ({ user, posts, setPosts }) {
function handleCreate (evt) {
evt.preventDefault()

const newPost = { title, content, author: user }
setPosts([ newPost, ...posts ])
dispatch({ type: 'CREATE_POST', title, content, author: user })
setTitle('')
setContent('')
}
Expand Down

0 comments on commit dc13c51

Please sign in to comment.