When the function has return value it works, if it is void it doesn't. How do I invoke void function like this when it is object's value?
Code with if-else statements:
const handlePageChange = (number, type) => {
const handlePage = () => setCurrentPage(number)
const handleAllLeft = () => setCurrentPage(1)
const handleAllRight = () => setCurrentPage(Math.ceil(data?.length / dataPerPage))
const handleLeft = () => {
if(currentPage === 1) setCurrentPage(1)
else setCurrentPage(currentPage - 1)
}
const handleRight = () => {
if(currentPage === Math.ceil(data?.length / dataPerPage)) setCurrentPage(Math.ceil(data?.length / dataPerPage))
else setCurrentPage(currentPage 1)
}
if(type === "page") handlePage()
if(type === "all-left") handleAllLeft()
if(type === "all-right") handleAllRight()
if(type === "left") handleLeft()
if(type === "right") handleRight()
}
Code with object literals:
const renderPagination = () => {
const pageNumbers = []
for (let i = 1; i <= Math.ceil(data?.length / dataPerPage); i ) {
pageNumbers.push(i)
}
const handlePageChange = (number, type) => {
const handlePage = () => setCurrentPage(number)
const handleAllLeft = () => setCurrentPage(1)
const handleAllRight = () => setCurrentPage(Math.ceil(data?.length / dataPerPage))
const handleLeft = () => {
if(currentPage === 1) setCurrentPage(1)
else setCurrentPage(currentPage - 1)
}
const handleRight = () => {
if(currentPage === Math.ceil(data?.length / dataPerPage)) setCurrentPage(Math.ceil(data?.length / dataPerPage))
else setCurrentPage(currentPage 1)
}
const obj = {
"page": handlePage(),
"all-left": handleAllLeft(),
"all-right": handleAllRight(),
"left": handleLeft(),
"right": handleRight()
}
return obj[type] || null
}
Tried returning null after state update, still no changes.
CodePudding user response:
A difference with your approaches is that the second one executes all the functions when you assign the object values
const obj = {
"page": handlePage(),
"all-left": handleAllLeft(),
"all-right": handleAllRight(),
"left": handleLeft(),
"right": handleRight()
}
If you want the same executions as in the first code, you can assign the functions, then execute the one you want on the return
const obj = {
"page": handlePage,
"all-left": handleAllLeft,
"all-right": handleAllRight,
"left": handleLeft,
"right": handleRight
}
return obj[type]() || null // <-- See extra parenthesis here