Skip to content

Commit

Permalink
useStateとuseEffectを使用したデータ取得からuseSWRへの移行
Browse files Browse the repository at this point in the history
  • Loading branch information
Takuya-Sakai91 committed Mar 30, 2024
1 parent 0c95535 commit 0fca47c
Showing 1 changed file with 31 additions and 116 deletions.
147 changes: 31 additions & 116 deletions app/javascript/components/GenerationUsers.jsx
Original file line number Diff line number Diff line change
@@ -1,127 +1,41 @@
import React, { useState, useEffect } from 'react'
import React from 'react'
import useSWR from 'swr'
import User from './User.jsx'
import Pager from './Pager.jsx'
import CSRF from 'csrf'

const getParams = () => {
const params = new URLSearchParams(location.search)
const result = {}
for (const [key, value] of params) {
result[key] = value
}
if (location.pathname.match(/tags/)) {
const tag = location.pathname.split('/').pop()
result.tag = tag
}
return result
}
import Pagination from './Pagination'
import usePage from './hooks/usePage'
import fetcher from '../fetcher'

export default function GenerationUsers({ generationID }) {
const [users, setUsers] = useState(null)
const [currentUser, setCurrentUser] = useState(null)
const [currentPage, setCurrentPage] = useState(Number(getParams().page) || 1)
const [totalPages, setTotalPages] = useState(0)
const [params] = useState(getParams())

useEffect(() => {
window.onpopstate = () => {
location.replace(location.href)
}
getUsers()
getCurrentUser()
}, [])

useEffect(() => {
getUsers()
}, [currentPage, params])

const getUsers = () => {
const url =
`/api/generations/${generationID}.json` +
(params.tag ? `tags/${params.tag}` : '') +
`?page=${currentPage}` +
(params.target ? `&target=${params.target}` : '') +
(params.watch ? `&watch=${params.watch}` : '')
fetch(url, {
method: 'GET',
headers: {
'Content-Type': 'application/json; charset=utf-8',
'X-Requested-With': 'XMLHttpRequest',
'X-CSRF-Token': CSRF.getToken()
},
credentials: 'same-origin',
redirect: 'manual'
})
.then((response) => response.json())
.then((json) => {
setUsers(json.users)
setCurrentUser(json.currentUser)
setTotalPages(json.totalPages)
})
.catch((error) => {
console.warn(error)
})
}

const getCurrentUser = () => {
fetch('/api/generations/&{generationID}', {
method: 'GET',
headers: {
'Content-Type': 'application/json; charset=utf-8',
'X-Requested-With': 'XMLHttpRequest',
'X-CSRF-Token': CSRF.getToken()
},
credentials: 'same-origin',
redirect: 'manual'
})
.then((response) => response.json())
.then((data) => setCurrentUser(data))
.catch((error) => console.error('Error fetching current user:', error))
}

const paginateClickCallback = (pageNumber) => {
setCurrentPage(pageNumber)
history.pushState(null, null, newUrl(pageNumber))
window.scrollTo(0, 0)
}

const newUrl = (pageNumber) => {
const url = new URL(location)
url.searchParams.set('page', pageNumber)
return url.toString()
}

useEffect(() => {
const page = new URLSearchParams(location.search).get('page')
if (page) setCurrentPage(Number(page))
}, [])
const itemsPerPage = 24
const { page, setPage } = usePage()
const { data, error } = useSWR(
`/api/generations/${generationID}.json?page=${page}&per=${itemsPerPage}`,
fetcher
)

const pagerProps = {
initialPageNumber: currentPage,
pageCount: totalPages,
pageRange: 5,
clickHandle: paginateClickCallback
}
if (error) return <>An error has occurred.</>
if (!data) return <>Loading...</>

return (
<div className="page-body">
{totalPages > 1 && (
<nav className="pagination">
<div className="container">
<Pager {...pagerProps} />
</div>
</nav>
{data.totalPages > 1 && (
<Pagination
sum={data.totalPages * itemsPerPage}
per={itemsPerPage}
page={page}
setPage={setPage}
/>
)}
<div className="container">
<div className="users row">
{users === null ? (
{data.users === null ? (
<div className="empty">
<i className="fa-solid fa-spinner fa-pulse" />
ロード中
</div>
) : users.length !== 0 ? (
users.map((user) => (
<User key={user.id} user={user} currentUser={currentUser} />
) : data.users.length !== 0 ? (
data.users.map((user) => (
<User key={user.id} user={user} currentUser={data.currentUser} />
))
) : (
<div className="row">
Expand All @@ -137,12 +51,13 @@ export default function GenerationUsers({ generationID }) {
)}
</div>
</div>
{totalPages > 1 && (
<nav className="pagination">
<div className="container">
<Pager {...pagerProps} />
</div>
</nav>
{data.totalPages > 1 && (
<Pagination
sum={data.totalPages * itemsPerPage}
per={itemsPerPage}
page={page}
setPage={setPage}
/>
)}
</div>
)
Expand Down

0 comments on commit 0fca47c

Please sign in to comment.