question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Items is [] when the component refreshes

See original GitHub issue

It seems that when you mount/unmount the component and the itemCount does not change the items is [] (after the first time).

A hacky way out of it is to do something like itemCount: myCount + Math.round(Math.random() * 100) and filter later.

In other words, some kind of check takes place based on the itemCount that causes cache-related (I presume) issues.

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Comments:37 (19 by maintainers)

github_iconTop GitHub Comments

1reaction
phaistoniancommented, Jun 18, 2021

@wellyshen Will try to make some time to do it later.

0reactions
abearief1405commented, Mar 20, 2022

Hai @wellyshen first things first I want to thankfull for the library.

I Had similiar issue with this. After successfull render the components, I move to other pages and back to the components, data wont to render it’s because isItemLoadedArr[loadIndex] = true.

So I used to const [isItemLoadedArr, setIItemLoadedArr] = useState([]); create useEffect

useEffect(() => {
    if (isItemLoadedArr.length > 0) {
        const resetIsLoaderArr = isItemLoadedArr.map((dt) => false)
        setIItemLoadedArr(resetIsLoaderArr)
    }

}, []) 

pass isItemLoadedArr to loadMore: (e) => loadData(e, setActivities, isItemLoadedArr) and the last things pass isItemLoadedArr to const loadData = async ({ loadIndex }, setActivities, isItemLoadedArr) => {...};

This also avoid the callback from being invoked repeatedly.

This is my full code:

import React, { useEffect, useState } from "react";
import useVirtual from "react-cool-virtual";
import axios from "axios";

const api = {
    xxx
}

const loadData = async ({ loadIndex }, setActivities, isItemLoadedArr) => {
    isItemLoadedArr[loadIndex] = true;

    try {
        const { data: activities } = await axios.get(`${api}/${loadIndex + 1}`);

        if (activities.data !== null) {
            setActivities((prevActivities) => {
                const nextActivities = [...prevActivities];

                activities.data.forEach((comment) => {
                    nextActivities[comment.id - 1] = comment;
                });

                return nextActivities;
            });
        } else {
            isItemLoadedArr[loadIndex] = false;
        }
    } catch (err) {
        isItemLoadedArr[loadIndex] = false;
        loadData({ loadIndex }, setActivities, isItemLoadedArr);
    }
};

const DataActivities = ({ total }) => {
    const cActivities = total;
    const batchActivities = 5;

    const [isItemLoadedArr, setIItemLoadedArr] = useState([]);
    const [activities, setActivities] = useState([]);
    const { outerRef, innerRef, items } = useVirtual({
        itemCount: cActivities,
        itemSize: 400,
        loadMoreCount: batchActivities,
        isItemLoaded: (loadIndex) => isItemLoadedArr[loadIndex],
        loadMore: (e) => loadData(e, setActivities, isItemLoadedArr)
    });

    useEffect(() => {
        if (isItemLoadedArr.length > 0) {
            const resetIsLoaderArr = isItemLoadedArr.map((dt) => false)
            setIItemLoadedArr(resetIsLoaderArr)
        }

    }, [])

    return (
        <div
            className="outer"
            style={{ width: "300px", height: "500px", overflow: "auto" }}
            ref={outerRef}
        >
            <div ref={innerRef}>
                {items.map(({ index, measureRef }) => (
                    <div
                        key={activities[index]?.id || `fb-${index}`}
                        className={`item ${index % 2 ? "dark" : ""}`}
                        style={{ padding: "16px", minHeight: "122px" }}
                        ref={measureRef} // Used to measure the unknown item size
                    >
                        {activities[index]
                            ? `${activities[index].id}. ${JSON.stringify(activities[index])}`
                            : "⏳ Loading..."}
                    </div>
                ))}
            </div>
        </div>
    );
};

export default DataActivities;

Hope it’s help, thank you.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Loosing component data on page refresh in react
... app starts (when you press F5, the page is refreshed, your React app is restarted so it loses all components states, contexts,...
Read more >
How to Refresh a Page or Component in React - Upmostly
The first way of refreshing a page or component is to use vanilla JavaScript to call the reload method to tell the browser...
Read more >
force:refreshView - Salesforce Lightning Component Library
To refresh a view, run $A.get('e.force:refreshView').fire(); , which reloads data for standard components. Custom components are refreshed with known ...
Read more >
Save State to LocalStorage & Persist on Refresh with React.js
Learn how to save React state and load it when a page refreshes using localStorage. We'll learn how to set up a simple...
Read more >
How to Save State to LocalStorage & Persist on Refresh with ...
React's state APIs give developers great ways to maintain personalization or the items you have in your shopping cart, but once you refresh...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found