I wanted to create pagination in React. All data comes from store. In this code I wanted to implement search engine. On this time I don't have this but i wrote search method which simulate that. OK, it works but - after I click hello, it display only items from category 2 but it display all the time this same pages (in my case 3). If I click 2 times more, it display only 1 page. I added setCountItems and setPages into search becouse this hooks doesn't update automaticlly.
import React, { useEffect, useState, useRef } from 'react'
import { connect} from 'react-redux'
import Article from './article'
const ArticlesContainer = ({ articles }) => {
const [allItems, setAllItems] = useState(articles.list);
const [pageNumber, setPageNumber] = useState(1);
const [perSite, setPerSite] = useState(10);
const [totalItems, setCountItems] = useState(allItems.length);
const from = (pageNumber - 1) * perSite;
const to = ((pageNumber - 1) * perSite) + perSite;
const [pages, setPages] = useState(Math.ceil(totalItems / perSite));
const handlePageClick = (i) => {
setPageNumber(i);
}
const search = () => {
setAllItems(allItems.filter(x => x.category=== 2 ));
setCountItems(allItems.length);
setPages(Math.ceil(totalItems / perSite));
}
const Pagination = ({pages}) => {
let list = []
for(let i = 1; i<=pages; i++){
list.push(<li key={i} onClick={() => handlePageClick(i)}>{i}</li>)
}
return list;
}
return (
<React.Fragment>
<a onClick={search}>Hello</a>
{allItems.slice(from, to).map(article =>
<Article key={article.id} article={article} />
)}
<div className="row">
<ul>
<Pagination pages={pages} />
</ul>
</div>
</React.Fragment>
);
}
const mapStateToProps = state => ({
articles: state.articles
})
export default connect(mapStateToProps, null)(ArticlesContainer);
Where problem is?
You seem to be suffering from a common misunderstanding of how State works in React. Updating state, whether via this.setState in class or via the "update function" returned by the useState hook, doesn't "automagically" change the relevant state value then and there. In class components, that's because of how React's implementation of setState works (it's asynchronous), but with Hooks it should be perfectly obvious if you stop to think about it. setAllItems is a function, while allItems is an array - and they don't have anything directly to do each other. Calling setAllItems doesn't change the value of allItems - because how could it? allItems is just a variable, the only way to give it a new value is to directly mutate or reassign it - clearly calling a separate function, setAllItems, with an argument that isn't allItems, can't possibly do that.
What it instead does is schedule a rerender of the component - that is, schedules a subsequent call of your function that represents the component - and ensures that the useState call corresponding to allItems will then return value you set. But this is necessarily a rather indirect process. In particular, allItems will have the value you want on the next render of your component, but that search function won't be called (until the user clicks the button again), so the setCountItems(allItems.length); call won't automatically trigger with the "correct" length (the updated length after filtering).
In your case the solution to the problem is very simple. You've overcomplicated your component by introducing far too many state variables, most of which are dependent on each other. Instead of const [totalItems, setCountItems] = useState(allItems.length);, just put const totalItems = allItems.length; - then this will automatically be recalculated to the correct value on every render. You've no need of a setCountItems function, as you know that it will always be equal to allItems.length - it doesn't vary independently.
Similarly, you can vastly simplify much else in this component, since the only things which can vary independently, and therefore which needs to be part of state, are the article list and the page number. This is how I would rewrite your component:
const perSite = 10;
const ArticlesContainer = ({ articles }) => {
const [allItems, setAllItems] = useState(articles.list);
const [pageNumber, setPageNumber] = useState(1);
const totalItems = allItems.length;
const from = (pageNumber - 1) * perSite;
const to = ((pageNumber - 1) * perSite) + perSite;
const pages = Math.ceil(totalItems / perSite);
const handlePageClick = (i) => {
setPageNumber(i);
}
const search = () => {
setAllItems(allItems.filter(x => x.category=== 2 ));
}
const Pagination = ({pages}) => {
let list = []
for(let i = 1; i<=pages; i++){
list.push(<li key={i} onClick={() => handlePageClick(i)}>{i}</li>)
}
return list;
}
return (
<React.Fragment>
<a onClick={search}>Hello</a>
{allItems.slice(from, to).map(article =>
<Article key={article.id} article={article} />
)}
<div className="row">
<ul>
<Pagination pages={pages} />
</ul>
</div>
</React.Fragment>
);
}
Related
I'm trying to make a page that gets picture from a server and once all pictures are downloaded display them, but for some reason the page doesn't re-render when I update the state.
I've seen the other answers to this question that you have to pass a fresh array to the setImages function and not an updated version of the previous array, I'm doing that but it still doesn't work.
(the interesting thing is that if I put a console.log in an useEffect it does log the text when the array is re-rendered, but the page does not show the updated information)
If anyone can help out would be greatly appreciated!
Here is my code.
export function Profile() {
const user = JSON.parse(window.localStorage.getItem("user"));
const [imgs, setImages] = useState([]);
const [num, setNum] = useState(0);
const [finish, setFinish] = useState(false);
const getImages = async () => {
if (finish) return;
let imgarr = [];
let temp = num;
let filename = "";
let local = false;
while(temp < num+30) {
fetch("/get-my-images?id=" + user.id + "&logged=" + user.loggonToken + "&num=" + temp)
.then(response => {
if(response.status !== 200) {
setFinish(true);
temp = num+30;
local = true;
}
filename = response.headers.get("File-Name");
return response.blob()
})
.then(function(imageBlob) {
if(local) return;
const imageObjectURL = URL.createObjectURL(imageBlob);
imgarr[temp - num] = <img name={filename} alt="shot" className="img" src={imageObjectURL} key={temp} />
temp++;
});
}
setNum(temp)
setImages(prev => [...prev, ...imgarr]);
}
async function handleClick() {
await getImages();
}
return (
<div>
<div className="img-container">
{imgs.map(i => {
return (
i.props.name && <div className="img-card">
<div className="img-tag-container" onClick={(e) => handleView(i.props.name)}>{i}</div>
<div className="img-info">
<h3 className="title" onClick={() => handleView(i.props.name)}>{i.props.name.substr(i.props.name.lastIndexOf("\\")+1)}<span>{i.props.isFlagged ? "Flagged" : ""}</span></h3>
</div>
</div>
)
})}
</div>
<div className="btn-container"><button className="load-btn" disabled={finish} onClick={handleClick}>{imgs.length === 0 ? "Load Images" : "Load More"}</button></div>
</div>
)
}
I think your method of creating the new array is correct. You are passing an updater callback to the useState() updater function which returns a concatenation of the previous images and the new images, which should return a fresh array.
When using collection-based state variables, I highly recommend setting the key property of rendered children. Have you tried assigning a unique key to <div className="img-card">?. It appears that i.props.name is unique enough to work as a key.
Keys are how React associates individual items in a collection to their corresponding rendered DOM elements. They are especially important if you modify that collection. Whenever there's an issue with rendering collections, I always make sure the keys are valid and unique. Even if adding a key doesn't fix your issue, I would still highly recommend keeping it for performance reasons.
It is related to Array characteristics of javascript.
And the reason of the console log is related with console log print moment.
So it should be shown later updated for you.
There are several approaches.
const getImages = async () => {
... ...
setNum(temp)
const newImage = [...prev, ...imgarr];
setImages(prev => newImage);
}
const getImages = async () => {
... ...
setNum(temp)
setImages(prev => JOSN.parse(JSON.object([...prev, ...imgarr]);
}
const getImages = async () => {
... ...
setNum(temp)
setImages(prev => [...prev, ...imgarr].slice(0));
}
Maybe it could work.
Hope it will be helpful for you.
Ok the problem for me was the server was not sending a proper filename header so it was always null so the condition i.props.name was never true... lol sorry for the confusion.
So the moral of this story is, always make sure that it's not something else in your code that causes the bad behavior before starting to look for other solutions...
I have a long process that updates the state. I want to show red background when it's running and blue when it's done.
const MapBuilder = (props) => {
const [backgroundColor, setBackgroundColor] = useState(false);
const [fancyResult, setFancyResult] = useState(null);
console.log(`stop 1 backgroundColor ${backgroundColor} fancyResult ${fancyResult}`)
const veryHardWork = () => {
setBackgroundColor("red");
console.log(`stop 2 backgroundColor ${backgroundColor} fancyResult ${fancyResult}`)
for (let i = 0; i < 1000; i++) {
for (let j = 0; j < 1000; j++) {
console.log("So hard")
}
}
setFancyResult("done")
console.log(`stop 3 backgroundColor ${backgroundColor} fancyResult ${fancyResult}`)
setBackgroundColor("blue")
console.log(`stop 4 backgroundColor ${backgroundColor} fancyResult ${fancyResult}`)
}
return (<div style={{background: backgroundColor}}>
<button className="btn btn-primary" onClick={veryHardWork}></button>
</div>)
}
Here is an output of such run
stop 1 backgroundColor false fancyResult null
MapBuilder.js:13 stop 2 backgroundColor false fancyResult null
10000MapBuilder.js:16 So hard
MapBuilder.js:20 stop 3 backgroundColor false fancyResult null
MapBuilder.js:22 stop 4 backgroundColor false fancyResult null
MapBuilder.js:10 stop 1 backgroundColor blue fancyResult done
I understand from this that the state change only happens after the method veryHardWork is finished. In my real project, I actually want to show a spinner the question is how can I do it if the state is only changed at the end of the method.
I think some clarification needs to be added. In reality, I allow the user to choose a file after the user chooses the file it is loaded and some heavy processing is performed on files data while the processing is running I want to show a spinner no Asyn work involved.
Some of the answers sugested to use useEffect and moving it to a promise I tryied both but it did not help here is a different take on it which also did not work
const MapBuilder = (props) => {
const [backgroundColor, setBackgroundColor] = useState(false);
const [fancyResult, setFancyResult] = useState(null);
const [startProcessing, setStartProcessing] = useState(null);
useEffect(() => {
let myFunc = async () => {
if (startProcessing) {
setBackgroundColor("red");
await hardWork();
setBackgroundColor("blue");
setStartProcessing(false);
}
}
myFunc();
}, [startProcessing])
const hardWork = () => {
return new Promise((resolve)=> {
for (let i = 0; i < 500; i++) {
for (let j = 0; j < 100; j++) {
console.log("So hard")
}
}
setFancyResult("sdsadsad")
resolve("dfsdfds")
})
}
return (<div style={{background: backgroundColor}}>
<button className="btn btn-primary" onClick={() => setStartProcessing(true)}></button>
</div>)
}
export default MapBuilder;
The problem with the approach is that the heavy calculation is happening at the main loop with the same priority. The red color change will not ever cause any changes until all things at the event handler have been finished.
With Reach 18 you can make your heavy calculation to be with lower priority and let the UI changes happen with normal priority. You can make this happen with minor change on your code base:
const veryHardWork = () => {
setBackgroundColor("red");
// Set heavy calculation to happen with lower priority here...
startTransition(() => {
console.log(`stop 2 backgroundColor ${backgroundColor} fancyResult ${fancyResult}`)
for (let i = 0; i < 1000; i++) {
for (let j = 0; j < 1000; j++) {
console.log("So hard")
}
}
setFancyResult("done")
setBackgroundColor("blue")
}
}
So I've made you a more real world example as the code you posted doesn't look like what you're actually wanting to achieve.
The scenario to my understanding is you want to preform some setup actions to get your state / data ready before showing it to the user.
cool, so first we will need some state to keep track of when we're ready to show content to the user lets call it isLoading. This will be a boolean that we can use to conditionally return either a loading spinner, or our content.
next we need some state to keep hold of our data, lets call this one content.
each state will be created from React.useState which can be imported with import { useState } from 'react';. We will then create variables in the following format:
const [state, setState] = useState(null);
nice, so now lets do somthing when the component mounts, for this we will use React.useEffect this hook can be used to tap into the lifecycle of a component.
inside our useEffect block we will preform our set up. In this case I'll say it's an async function that get some data from an API and then sets it to state.
lastly we will use our isLoading state to decide when we're ready to show the user something more interesting than a spinner.
All together we get something like this:
import { useState, useEffect } from 'react';
const MyComponent = () => {
// create some state to manage when what is shown
const [isLoading, setIsLoading] = useState(true);
// create some state to manage content
const [content, setContent] = useState(null);
// when the component is mounted preform some setup actions
useEffect(() => {
const setup = async () => {
// do some setup actions, like fetching from an API
const result = await fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(r => r.json());
// update our state that manages content
setContent(result);
// when we are happy everything is ready show the user the content
setIsLoading(false);
};
// run our setup function
setup();
}, [ ]);
// if we are not yet ready to show the user data, show a loading message
if (isLoading) {
return (
<div>
<p>spinner goes in this div</p>
</div>
)
}
// when we are ready to show the user data is will be shown in this return statement
return (
<div>
<p>this div will show when the `isLoading` state is true and do something with the content state is wanted</p>
</div>
)
}
I believe you'll find this more useful than the example you provided
You already control state of fancyResult,
or you can use showSpinner state for only reason to show spinner
You can use for long progress Promise [Link] And Async/Await [Link]
const veryHardWork = async () => {
setBackgroundColor("red");
const awaiting = await new Promise((resolve, reject) => {
for (let i = 0; i < 1000; i++) {
for (let j = 0; j < 1000; j++) {
resolve(console.log("So hard"));
}
}
})
// After Finished Awating Hardwork
setFancyResult("done");
setBackgroundColor("blue") ;
}
return (
<div style={{background: fancyResult === 'done' ? 'blue': 'red'}}>
<button className="btn btn-primary" onClick={veryHardWork}></button>
{ fancyResult === 'done' && 'Show Spinner' }
</div>
)
Try this:
import { useState, useEffect } from "react";
import { flushSync } from "react-dom";
const MapBuilder = (props) => {
const [backgroundColor, setBackgroundColor] = useState(false);
const [fancyResult, setFancyResult] = useState(null);
// this will only be called on the first mount
useEffect(() => {
console.log(
`backgroundColor ${backgroundColor} fancyResult ${fancyResult}`
);
}, [backgroundColor, fancyResult]);
const veryHardWork = () => {
setBackgroundColor("red");
setTimeout(() => {
for (let i = 0; i < 1000; i++) {
for (let j = 0; j < 1000; j++) {
for (let k = 0; k < 1000; k++) {
// console.log("So hard");
}
}
}
setFancyResult("done");
// flushSync(() => setFancyResult("done"));
console.log(
`inside closure - OUTDATED: backgroundColor ${backgroundColor} fancyResult ${fancyResult}`
);
setBackgroundColor("blue");
}, 0);
};
return (
<div style={{ background: backgroundColor }}>
<button className="btn btn-primary" onClick={veryHardWork}>
Work!
</button>
</div>
);
};
export default MapBuilder;
CodeSandbox
Explanation:
Unblocking the UI thread
In order for the color to change to red, the UI thread must be freed up to
make the state changes (set background color to red) and
do the re-render.
One way to achieve this is by using setTimeout. This puts a function on a queue to be run later, allowing the UI thread to finish the above 2 tasks before tackling the actual work. You should note though, this doesn’t actually run your work on a new thread, so once the work starts getting done, the UI will be unresponsive until the work is done. Consider using a Web Worker to solve this in the future.
Logging the current state
The other thing to understand about React is that every time a re-render occurs, the entire function ('MapBuilder’ in this case) is re-run. This means that your ‘stop 1’ message will be displayed every re-render, and therefore every time the state changes.
Additionally, logging the state from within veryHardWork will log the state when the function was defined. This means that the value will be outdated, i.e. stale. This is because of a functional concept called closures. From Wikipedia “Unlike a plain function, a closure allows the function to access those captured variables through the closure's copies of their values or references, even when the function is invoked outside their scope.”
So how should we log the current state when it is changed? By using the useEffect hook. This function will be re-run whenever any of the dependencies change ([backgroundColor, fancyResult] in this case).
Console.log undefined behavior
Another thing to note is that many console.logs should not be used as the ‘work’. The rendering of the log will happen asynchronously, so ‘firing’ the logs will be much quicker than they will actually show up. This leads the observer watching the console to think that the ‘red’ stage has been skipped. Instead, we can just loop more times, or do some math in the loop, etc (which is closer to what your actual synchronous work will be anyway). In fact, console.log seems to be quite unpredictable, as noted here.
Automatic Batching
You might be wondering why “done” and “blue” show up as a single state update (i.e. stop 3 and 4 happen at the same time). This is because of automatic batching. As a performance optimization, react attempts to ‘batch’ state changes to prevent additional re-renders. To prevent this behavior, you can uncomment line 27 flushSync(() => setFancyResult("done”)). This is not necessary for this use-case, as the batching is appropriate here, but it’s helpful to understand what’s going on.
I've gone through multiple useRef/useEffect instructions but I just can't seem to make it work here.
The code workflow here is: Remix/React, get data from database, display data, turn data into a ticker that can be updated
If anyone could point out any glaring errors they see in this code as to why the useEffect hook isn't firing, or why the useRef hook can never find the {listRef} within the <ul>, I would love to know.
import { Links, redirect, useLoaderData, Outlet } from 'remix'
import { db } from '~/utils/db.server'
import { getUser } from '~/utils/session.server'
import { ReactSortable } from "react-sortablejs"
import { useState, useRef, useEffect } from 'react'
import tickerStylesUrl from '~/styles/tickerDisplay.css'
export const links = () => [{ rel: 'stylesheet', href: tickerStylesUrl }]
export const loader = async ({ request, params }) => {
const user = await getUser(request)
const ticker = await db.ticker.findUnique({
where: { id: params.tickerId },
include: {
headlines: true,
},
})
if (!ticker) throw new Error('Ticker not found')
const data = { ticker, user }
return data
}
export const action = async ({ request, params }) => {
}
// The ticker function displays the items without styling, so it finds the database perfectly and can get the data
function displayTicker() {
const { ticker, user } = useLoaderData()
const headlines = ticker.headlines
const tickerParentStyle = {
width: "1920px",
height: "1080px",
position: "relative",
backgroundColor: "black"
}
const tickerStyle = {
position: "absolute",
padding: "0",
bottom: "0",
color: `${ticker.fontColor}`,
backgroundColor: `${ticker.backgroundColor}`,
fontFamily: `${ticker.font}`,
fontSize: "2em",
}
const tickerHeadlineStyle = {
margin: "auto",
height: "50%",
}
console.log("Headlines: " + headlines)
// So begins the found ticker code I had hoped to integrate
// Source: https://www.w3docs.com/tools/code-editor/2123
function scrollTicker() {
const marquee = listRef.current.querySelectorAll('.tickerHeadlines');
let speed = 4;
let lastScrollPos = 0;
let timer;
marquee.forEach(function (el) {
const container = el.querySelector('.headlineItem');
const content = el.querySelector('.headlineItem > *');
//Get total width
const elWidth = content.offsetWidth;
//Duplicate content
let clone = content.cloneNode(true);
container.appendChild(clone);
let progress = 1;
function loop() {
progress = progress - speed;
if (progress <= elWidth * -1) {
progress = 0;
}
container.style.transform = 'translateX(' + progress + 'px)';
container.style.transform += 'skewX(' + speed * 0.4 + 'deg)';
window.requestAnimationFrame(loop);
}
loop();
});
window.addEventListener('scroll', function () {
const maxScrollValue = 12;
const newScrollPos = window.scrollY;
let scrollValue = newScrollPos - lastScrollPos;
if (scrollValue > maxScrollValue) scrollValue = maxScrollValue;
else if (scrollValue < -maxScrollValue) scrollValue = -maxScrollValue;
speed = scrollValue;
clearTimeout(timer);
timer = setTimeout(handleSpeedClear, 10);
});
function handleSpeedClear() {
speed = 4;
}
}
const listRef = useRef()
console.log("listRef: " + JSON.stringify(listRef))
// This console appears everytime, but is always empty, presumably because DOM has just rendered
useEffect(() => {
console.log("useEffect fired")
// This console NEVER fires, sadly. I thought this would happen ONCE rendered
}, [listRef]);
return (
<>
<Links />
<div style={tickerParentStyle}>
<div style={tickerStyle}>
<div key={ticker.id} style={tickerHeadlineStyle} class="tickerWrapper">
// HERE IS THE TARGET UL
<ul className="tickerHeadlines" ref={listRef} style={{ margin: "10px 0 10px 0" }} >
{/* Hoping to map through the ticker items here, and have them displayed in a list, which would then be manipulated by the useRef/useEffect hook */}
{headlines.map((headline) => (
<>
<li class="headlineItem" key={headline.id}>
<span>
{headline.content} {ticker.seperator}
</span>
</li>
</>
))}
{scrollTicker()}
</ul>
</div>
</div>
</div>
</>
)
}
export default displayTicker
As always, any help is appreciated.
useRef is a hook that is used to access DOM elements, manipulating the DOM directly in a React application breaks the whole point of declarative programming. It is not at all advised to manipulate DOM directly using any dom objects and methods such as document. Coming to the useEffect hook, the useEffect hook runs conditionally depending on what's supplied in the dependency array, if none, the hook runs only once after the component finishes mounting. So you should be careful regarding what needs to be passed to the useEffect dependency array. Considering your case, when you pass listRef, the useEffect runs only when there is a change in the object and not it's properties, because objects are non-primitive, any changes in the property is not treated as a change in the object, and its merely an object property mutation that doesn't cause re-render. To steer clear, you should be sure of, when exactly you want it to be invoked, as you mentioned, you'd want it to run right after the data has rendered, you could instead use headlines in your dependency array.
Change the dependency array to include headlines.
useEffect(() => {
console.log("useEffect fired")
// This console NEVER fires, sadly. I thought this would happen ONCE rendered
}, [headlines]);
Alternatively, you could also leave it empty, making it run only once after the component has mounted.
useEffect(() => {
console.log("useEffect fired")
// This console NEVER fires, sadly. I thought this would happen ONCE rendered
}, []);
A caveat, the former snippet would run every time there's a change in headlines, and the latter would run only once no matter what changes.
So, depending on your use case, you might want to choose the one that best suits your needs.
There are a couple of things to code make code better:
initiate ref with 'null' value
call your 'scrollTicker' function inside useEffect Hook.
always remove listeners when component demount. Follow https://reactjs.org/docs/hooks-reference.html#useeffect for more details
you can use useEffect hook like this:
useEffect(() => {
// use your ref here.
return () => {
// Remove linteners
};
});
I am working on a react app where I have table with scroller and on every scroll I am updating the page number and making a subsquent api call with the updated page number but the page number is updating so fast that it exceeds the limit of page number and the api returns empty array and that leads to imcomplete data.
Here's my code:
handleScroll=async ({ scrollTop }) => {
console.log('hey');
if (this.props.masterName && this.props.codeSystem) {
const params = {};
await this.props.setPageNumber(this.props.page_num + 1);
params.code_system_category_id = this.props.masterName;
params.code_systems_id = this.props.codeSystem;
params.page_num = this.props.page_num;
if (this.props.entityName) params.entity_name = this.props.entityName;
if (this.props.status) params.status = this.props.status;
console.log(params);
await this.props.fetchCodeSets(params);
}
}
This is the function that will get called on every scroll,on every scroll I am incrementing the page number by 1 using await and also making a api call as this.props.fetchCodeSets using await so that scroll doesnt exceed before completing the api call,but the scroll keeps getting called and it leads to the above explained error.
Here's my table with scroll:
<StyledTable
height={250}
width={this.props.width}
headerHeight={headerHeight}
rowHeight={rowHeight}
rowRenderer={this.rowRenderer}
rowCount={this.props.codeSets.length}
rowGetter={({ index }) => this.props.codeSets[index]}
LoadingRow={this.props.LoadingRow}
overscanRowCount={5}
tabIndex={-1}
className='ui very basic small single line striped table'
columnsList={columns}
onScroll={() => this.handleScroll('scroll')}
/>
I am using react-virtualized table and the docs can be found here:
https://github.com/bvaughn/react-virtualized/blob/master/docs/Table.md
Any leads can definitely help!
You are loading a new page on every scroll interaction. If the user scrolls down by 5 pixels, do you need to load an entire page of data? And then another page when the scrolls down another 2 pixels? No. You only need to load a page when you have reached the end of the available rows.
You could use some math to figure out which pages need to be loaded based on the scrollTop position in the onScroll callback and the rowHeight variable.
But react-virtualized contains an InfiniteLoader component that can handle this for you. It will call a loadMoreRows function with the startIndex and the stopIndex of the rows that you should load. It does not keep track of which rows have already been requested, so you'll probably want to do that yourself.
Here, I am storing the API responses in a dictionary keyed by index, essentially a sparse array, to support any edge cases where the responses come back out of order.
We can check if a row is loaded by seeing if there is data at that index.
We will load subsequent pages when the loadMoreRows function is called by the InfiniteList component.
import { useState } from "react";
import { InfiniteLoader, Table, Column } from "react-virtualized";
import axios from "axios";
const PER_PAGE = 10;
const ROW_HEIGHT = 30;
export default function App() {
const [postsByIndex, setPostsByIndex] = useState({});
const [totalPosts, setTotalPosts] = useState(10000);
const [lastRequestedPage, setLastRequestedPage] = useState(0);
const loadApiPage = async (pageNumber) => {
console.log("loading page", pageNumber);
const startIndex = (pageNumber - 1) * PER_PAGE;
const response = await axios.get(
// your API is probably like `/posts/page/${pageNumber}`
`https://jsonplaceholder.typicode.com/posts?_start=${startIndex}&_end=${
startIndex + PER_PAGE
}`
);
// This only needs to happen once
setTotalPosts(parseInt(response.headers["x-total-count"]));
// Save each post to the correct index
const posts = response.data;
const indexedPosts = Object.fromEntries(
posts.map((post, i) => [startIndex + i, post])
);
setPostsByIndex((prevPosts) => ({
...prevPosts,
...indexedPosts
}));
};
const loadMoreRows = async ({ startIndex, stopIndex }) => {
// Load pages up to the stopIndex's page. Don't load previously requested.
const stopPage = Math.floor(stopIndex / PER_PAGE) + 1;
const pagesToLoad = [];
for (let i = lastRequestedPage + 1; i <= stopPage; i++) {
pagesToLoad.push(i);
}
setLastRequestedPage(stopPage);
return Promise.all(pagesToLoad.map(loadApiPage));
};
return (
<InfiniteLoader
isRowLoaded={(index) => !!postsByIndex[index]}
loadMoreRows={loadMoreRows}
rowCount={totalPosts}
minimumBatchSize={PER_PAGE}
>
{({ onRowsRendered, registerChild }) => (
<Table
height={500}
width={300}
onRowsRendered={onRowsRendered}
ref={registerChild}
rowCount={totalPosts}
rowHeight={ROW_HEIGHT}
// return empty object if not yet loaded to avoid errors
rowGetter={({ index }) => postsByIndex[index] || {}}
>
<Column label="Title" dataKey="title" width={100} />
<Column label="Description" dataKey="body" width={200} />
</Table>
)}
</InfiniteLoader>
);
}
CodeSandbox Link
The placeholder API that I am using takes start and end indexes instead of page numbers, so going back and forth from index to page number to index in this example is silly. But I am assuming that your API uses numbered pages.
I have a React app that does 3 things; displays the elements in an array, adds an element on button press and removes an element on button press.
Inside of my image, I am displaying my local .gif file. My .gif file is a single animation .gif, I turned off infinite looping because I want the .gif to spawn in and then remain static.
My error comes when I add a second .gif element to my array. Only the first element displays its animation and the rest display the final slide in the .gif.
I believe that I may be able to solve my issue if I manage to instantiate the element but I am not sure how I would go about doing that.
Here is an excerpt from my code::
function App(){
const [numbValue, numbUpdate] = useState(0);
const [starsValue, starsUpdate] = useState(null);
function DisplayGIF(numbToDisp){
let value=[];
for(let i=0;i<numbToDisp;i++){
value.push(<img className="icon" src={process.env.PUBLIC_URL + "/once-star-filled.gif"} alt="animated star"/>)
}
starsUpdate(<>{value.map(element=>{return element;})}</>);
}
function Add(){
numbUpdate(numbValue+1);
DisplayGIF(numbValue+1);
}
function Sub(){
numbUpdate(numbValue-1);
DisplayGIF(numbValue-1);
}
return(<>
<p onClick={Add}>+</p>
{starsValue}
<p onClick={Sub}>-</p>
</>);
}
Output::
First add :: displays 1 image that is animated until the end
Consecutive adds :: displays x images that display the final frame in the animation
Please, try this one.
function App() {
const [stars, setStars] = useState(0);
return (
<React.Fragment>
<p onClick={() => setStars((s) => s + 1)}>+</p>
{new Array(stars).fill().map((s, ind) => {
return <Star key={ind}></Star>;
})}
<p onClick={() => setStars((s) => (s === 0 ? 0 : s - 1))}>-</p>
</React.Fragment>
);
}
export function Star(props) {
const [id] = useState(Math.random()); // Generate unique id for this item
return (
<img
className="icon"
src={`${process.env.PUBLIC_URL}/once-star-filled.gif?id=${id}`}
alt="animated star"
/>
);
}
I fix some notation errors, like function name should be started from small letter.
Moreover, you could use only one state to store and render stars gif.
Also, it is better to create another React function element <Star />. In this way you can reuse this gif later, and add some props, for instance different alter text, src attribute and et al.
[Update 1]
I disagree with #Karl comment, there is a significant flaw in his solution: when the src is formed using the ind, elements will be animated only once (ex: remove element with ind=2 and add again element with ind=2 give us a static image).
So I decided to supplement my answer with one more option, which I would not use in production, but it is interesting and solves the OP's problem.
What is the new solution? We fetch the image through fetch, convert it to dataUrl, delete the first part represented metadata, and pass it to the Star elements for rendering as src props.
Each element adds meta-information with its own Id, which does not affect the file itself, but the browser perceives the picture as new. Therefore, all start animates every time their appear on page.
import React, { useState, useRef } from "react";
import "./App.css";
function App() {
const [stars, setStars] = useState(0);
const [data, setData] = useState(null);
const ref = useRef(null);
React.useEffect(() => {
fetch("./ezgif-2-110436c6c12b.gif")
.then((res) => res.blob())
.then(async (text) => {
const reader = new FileReader();
reader.onload = (ev) => {
setData(
ev.currentTarget.result.replace("data:image/gif;base64", "")
);
};
reader.readAsDataURL(text);
});
}, []);
return (
<React.Fragment>
<p onClick={() => setStars((s) => s + 1)}>+</p>
{data &&
new Array(stars).fill().map((s, ind) => {
return <Star src={data} key={ind}></Star>;
})}
<p onClick={() => setStars((s) => (s === 0 ? 0 : s - 1))}>-</p>
</React.Fragment>
);
}
/**
*
* #param {{src: string}} props
* #returns
*/
export function Star(props) {
const [id] = useState(Math.random());
return (
<img
className="icon"
src={`data:image/gif;base64;${id}` + props.src}
alt="animated star"
/>
);
}
export default App;