Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactored home.js using useReducer hook #167

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 21 additions & 8 deletions src/pages/Home.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { useState, useEffect, useContext } from 'react'
import React, { useState, useEffect, useContext, useReducer } from 'react'
import { Link } from '@reach/router'
import { Helmet } from 'react-helmet'

Expand All @@ -10,14 +10,27 @@ import useAuth from '../hooks/useAuth'
import Context from '../modules/Context'
import userStory from '../services/user_story'

const initialState = { modal: false }

function reducer(state, action) {
switch (action.type) {
case 'openModal':
return { modal: true }
case 'closeModal':
return { modal: false }
default:
throw new Error()
}
}

const Home = () => {
const { logout } = useAuth()

const userId = localStorage.getItem('id')

const { dispatch } = useContext(Context)

const [modal, setModal] = useState(false)
const [state, dispatchState] = useReducer(reducer, initialState)

const [policyUpdate, setPolicyUpdate] = useState()

Expand All @@ -32,7 +45,7 @@ const Home = () => {
response.data.data.userStoryNotifications.length &&
!seenBy.includes(userId)
) {
setModal(true)
dispatchState({ type: 'openModal' })
setPolicyUpdate(response.data.data.userStoryNotifications[0])
}
}
Expand All @@ -46,7 +59,7 @@ const Home = () => {
const seenBy = policyUpdate.seenBy.map((seen) => seen.id)
seenBy.push(userId)
await userStory.markNotificationAsRead(policyUpdate.id, seenBy)
setModal(false)
dispatchState({ type: 'closeModal' })
}

const handlePolicyUpdateReject = async () => {
Expand All @@ -56,7 +69,7 @@ const Home = () => {
type: 'DEAUTHENTICATE'
})
}
setModal(false)
dispatchState({ type: 'closeModal' })
}

return (
Expand Down Expand Up @@ -89,12 +102,12 @@ const Home = () => {
<Stories />
</div>
</div>
{modal && policyUpdate ? (
{state.modal && policyUpdate ? (
<Modal
showButtons={true}
onCancel={handlePolicyUpdateReject}
isActive={modal}
show={() => setModal(false)}
isActive={state.modal}
show={() => dispatchState({ type: 'closeModal' })}
onOk={acceptUpdatedPolicy}
>
{
Expand Down