score:3
Accepted answer
i fixed pagination with filter with the help of usememo hook. the problem was that i was filtering the default array and i wasn't updating the totaltodos with the length of computed todos etc.. now inside usememo hook, i compute(filter) the todos first and then i update totaltodos with the length of computed todos.
import { usestate, useeffect, usememo } from "react";
import axios from "axios";
import "./styles.css";
export default function app() {
const [todos, settodos] = usestate([]);
const [searchterm, setsearchterm] = usestate("");
const [filtercompleted, setfiltercompleted] = usestate("");
const [currentpage, setcurrentpage] = usestate(1);
const [totaltodos, settotaltodos] = usestate(0);
const todosperpage = 10;
useeffect(() => {
axios
.get(`https://jsonplaceholder.typicode.com/todos`)
.then((response) => {
settodos(response.data);
})
.catch((error) => {
console.log(error);
});
}, []);
const pagenumbers = [];
for (let i = 1; i <= math.ceil(totaltodos / todosperpage); i++) {
pagenumbers.push(i);
}
const todosdata = usememo(() => {
let computedtodos = todos;
if (searchterm) {
computedtodos = computedtodos.filter(
todo =>
todo.title.tolowercase().includes(searchterm.tolowercase())
);
}
if (filtercompleted === "true") {
computedtodos = computedtodos.filter(
todo =>
filtercompleted === "true" && todo.completed === true
)
}
if (filtercompleted === "false") {
computedtodos = computedtodos.filter(
todo =>
filtercompleted === "false" && todo.completed === false
)
}
settotaltodos(computedtodos.length);
//current page slice
return computedtodos.slice(
(currentpage - 1) * todosperpage,
(currentpage - 1) * todosperpage + todosperpage
);
}, [todos, currentpage, searchterm, filtercompleted]);
// change page
const paginate = (pagenumber) => setcurrentpage(pagenumber);
const resetfilter = () => {
setsearchterm("");
setfiltercompleted("");
setcurrentpage(1);
};
return (
<div classname="container">
<h3>filters</h3>
<div classname="mb-3">
<label htmlfor="search" classname="form-label">
search
</label>
<input
type="text"
classname="form-control"
id="search"
placeholder="search title"
value={searchterm}
onchange={(e) => {
setsearchterm(e.target.value);
setcurrentpage(1);
}}
/>
</div>
<div classname="mb-3">
<label htmlfor="search" classname="form-label">
completed
</label>
<select
classname="form-select"
value={filtercompleted}
onchange={(e) => {
setfiltercompleted(e.target.value);
setcurrentpage(1);
}}
>
<option defaultvalue=""></option>
<option value="true">true</option>
<option value="false">false</option>
</select>
</div>
<div classname="mb-3">
<button
type="button"
classname="btn btn-danger btn-sm"
onclick={resetfilter}
>
reset filters
</button>
</div>
<nav>
<ul classname="pagination">
{pagenumbers.map((number) => (
<li key={number} classname="page-item">
<button onclick={() => paginate(number)} classname="page-link">
{number}
</button>
</li>
))}
</ul>
</nav>
{todosdata
.map((todo) => {
return (
<div key={todo.id} classname="card margin-bottom">
<h5 classname="card-header">
<div classname="card-header-flex">
<span classname="id">{`#${todo.id}`}</span>
</div>
</h5>
<div classname="card-body">
<div classname="card-text">
<div classname="card-body-flex">
<span>{`title: ${todo.title}`}</span>
<span>{`completed: ${todo.completed}`}</span>
</div>
</div>
</div>
</div>
);
})}
</div>
);
}
Source: stackoverflow.com
Related Query
- How to implement pagination with filter in React
- ReactJS - How can I implement pagination for react with keep state when route change?
- How to implement pagination in React JS with REST API
- How to implement pagination in React
- How to implement Error Boundary with React Hooks Component
- How to implement skipWaiting with Create React App?
- How to implement Stripe with React Native?
- How to implement componentDidMount with hooks in React to be in line with the EsLint rule "react-hooks/exhaustive-deps": "warn"?
- How to implement the OAuth2 Authorization code grant with PKCE for a React single page application?
- How to implement a scrollspy with React
- How to implement a gameloop with requestAnimationFrame across multiple React Redux components?
- How can I implement SSO Authentication with Active Directory in React App?
- How to implement pagination for react by semantic-ui-react
- How to implement react with on type (realtime) emojis?
- react native how to filter data with some key object on json
- How to implement a scrollspy in react native with ScrollView?
- How to implement share to twitter with react js
- How do you implement "check all" in React with child components?
- How can we implement an Open with Postman button to open a postman collection link sent from a third party react application?
- How to implement Firebase authentication with React Redux?
- How to implement react routing with bootstrap navbar component?
- How to properly implement "subscription"-like fetches with React useEffect
- How to use the history to update the pagination bar with react router?
- How to implement a React Component with sub-components and call them?
- How to implement a server side pagination with Material ui and react?
- React hooks pagination with useEffect - how to revert page number if request fails?
- How to implement Regex filter in a React search bar?
- How to implement error boundary in react with server side rendering in nextjs?
- how to implement a refresh button with React Hooks?
- how to implement react js pagination
More Query from same tag
- How to config webpack to transpile files from other lerna packages (ejected from create-react-app)
- React JS how to remember the clicked item in a list when I pass to next page
- Problems with PUT request in react.js application
- How to reduce duplicative calls to callback functions in componentDidUpdate
- Getting 'Can't call setState on a component that is not yet mounted' in a very simple react exercise
- Cypress React, cannot find root element to mount the component
- placing input values into array object
- Empty shouldComponentUpdate works, otherwise not?
- Change the font size of the placeholder
- Can't perform a React state update on an unmounted component
- Firebase onAuthStateChanged is being called twice upon login
- React state and conditional rendering
- Update a "UseContext array" fail to re-render/generate a new component
- Bootstrap react ./node_modules/bootstrap/dist/js/bootstrap.min.js Module not found: Can't resolve 'jquery'
- Use Refs In Material UI
- How can I access cookie information inside a component rendered on _app.js in next
- How to select the last element which is of the component's type in styled-components
- how to re render a list after updating an array state in a position in between (not at top or bottom in the list)?
- How can I replace the Select ... by Select an option in a react multi select?
- Do functions not update React hooks (particularly useState) depending on how they are called?
- React "cannot access 'variable' before initialization" with useState callback
- Uncaught TypeError: Cannot read property 'photo' of undefined
- Triggering action on route change with react-router
- Pass class object to ReactJS component
- React JS: How do I create a downloadable link with PDF documents to download?
- login page authentication ReactJs
- Mapped data containing buttons throwing "TypeError: Cannot read property 'onSubmit' of undefined"
- Context API not displaying array of data
- React.js - audio.duration returns NaN & How to upload blobUrl to amazon s3
- how does a component gets props from a reducer in redux(how does the connect function work)