Home > Software design >  React FlatList keeps loading the same database array record over and over again
React FlatList keeps loading the same database array record over and over again

Time:12-14

I've been tring to load a list of items from a database onto a FlatList, but the FlatList keeps loading repetedly indefinetly.

Say the list contains only 10 items - it will load the 10, then start again from 1 - 10, over and over.

How can I prevent this and only load the 10 items only once?

Thank you all in advance.

Here's how I'm going about it :

import {View, FlatList} from 'react-native';
import React, {useState} from 'react';

export const MyFunctionalComponent = () => {
  [dBList, setDBList] = useState(null);

  let getMyDbList = () => {
    return getDbList();
  };

  new Promise((res, rej) => {
    let myDbList = getMyDbList();
    res(myDbList);
  }).then(result => {
    setDBList(result);
  });

  const renderItem = ({item}) => {
    return (
      <View key={item.myGUID.toString()} />
    );
  };

  return (
    <View>
      {dBList && (
        <FlatList
          data={dBList}
          renderItem={renderItem}
          keyExtractor={item => {
            item.myGUID.toString();
          }}
        />
      )}
    </View>
  );
};

CodePudding user response:

Because your promise declares in the root level, which will be executed every time the component is rendered. Just move this to useEffect to load only once

useEffect(() => {
 new Promise((res, rej) => {
    let myDbList = getMyDbList();
    res(myDbList);
  }).then(result => {
    setDBList(result);
  });
}, [])

CodePudding user response:

It looks like the problem is that you are calling getMyDbList and setting the state inside of a new Promise every time your functional component is rendered. This causes the getDbList function to be called repeatedly, resulting in the FlatList rendering repeatedly.

To fix this, you should move the code that calls getDbList and updates the dBList state to a separate method, such as the useEffect hook. The useEffect hook will be called only when the component is initially rendered, so it will prevent the FlatList from re-rendering indefinitely.

Here's how you can modify your code to fix the problem:

useEffect(() => {
    // this block of code will only be executed when the component is mounted
    let getMyDbList = () => {
      return getDbList();
    };

    new Promise((res, rej) => {
      let myDbList = getMyDbList();
      res(myDbList);
    }).then(result => {
      setDBList(result);
    });
  }, []); // the empty array here tells the useEffect hook to only run the code when the component is mounted
  • Related