0

I work on a basic infinite scroll and I've got a problem getting the data from Items.

It works in my useEffect call, I console.log it, and everything is there. But then the value set to 1... why? Thanks

const List = () => {

    const [Items, setItems] = useState([]);
    const [fetchData, setFetchData] = useState((listSize > lot) ? lot : listSize);
    const [Limits, setLimits] = useState(true);

    console.log(Items); // got empty first time and then 1

    useEffect(() => {
        let nvxPic = list.slice(fetchData - lot, fetchData);
        setItems(Items.push(nvxPic.map((image, key) => (
            <img key={key} src={`Images/${image}`} alt="" />
        ))))
        console.log(Items); // got my array
    }, [fetchData])

    const fetchMoreData = async () => {
        if (fetchData + lot > listSize) {
            setFetchData(listSize);
            setLimits(false);
        }
        else
            setFetchData(fetchData + lot);
    };

    return (
        <div>
            <InfiniteScroll
                dataLength={fetchData}
                next={fetchMoreData}
                hasMore={Limits}
                loader={<h4>Loading...</h4>}
                endMessage={
                    <p style={{ textAlign: "center" }}>
                        <b>Done</b>
                    </p>
                }
            >
                {Items}
            </InfiniteScroll>
        </div>
    );
};
mruanova
  • 6,351
  • 6
  • 37
  • 55
policy
  • 3
  • 1

1 Answers1

0

The issue is happening because of this part of the code:

setItems(Items.push(nvxPic.map((image, key) => (
   <img key={key} src={`Images/${image}`} alt="" />
)));

The code sets the value of the Items variable to the length of the new array what push returned. That's why you are getting the 1 as the value for the variable.

As the documentation Array.prototype.push() states:

The push() method adds one or more elements to the end of an array and returns the new length of the array.

map creates a new array for you, I guess you don't need to push it anyway.

From Array.prototype.map() documentation you can see:

The map() method creates a new array with the results of calling a provided function on every element in the calling array.

I think the solution is, just simply remove the push part from the code:

setItems(nvxPic.map((image, key) => (
   <img key={key} src={`Images/${image}`} alt="" />
));

So map returns the new array then setItems is updating the value of Items variable, you don't need to do that with push.

norbitrial
  • 14,716
  • 7
  • 32
  • 59