[SOLVED] Render countdowns on each flat list item

Issue

I’m doing an auctions app with react-native and Firebase, I’m using a FlatList to render each auction component.

On each auction component want to show a countdown with the reminder time, I’m retrieving the end date of the auction from Firebase.

But if I update the state every second, of each of my auction components my app gets really slow.

Is there a better way to do that?

Solution

I have many intervals running one for each of my components in the flat list

You can move the timer to the component with FlatList so that you only have one timer.

Also make sure the interval is set in componentDidMount and cleared in componentWillUnmount.

class App extends React.Component {
  state = {
    timeElapsed: 0,
  };
  componentDidMount() {
    this.interavl = setInterval(
      () => this.setState((prev) => ({ timeElapsed: prev.timeElapsed + 1 })),
      1000,
    );
  }
  componentWillUnmount() {
    clearInterval(this.interval);
  }
  render() {
    return <FlatList renderItem={() => <Child timeElapsed={this.state.timeElapsed} />} />;
  }
}

const Child = (props) => <Text>{props.timeRemaining - props.timeElapsed}</Text>;

Answered By – Roy Wang

Answer Checked By – Timothy Miller (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *