Art Art - 1 year ago 75
React JSX Question

Meteor / ReactJS - UI blinking issue: rendering twice before and after checking a database

Task: I need to show components based on a database result.
Issue: It renders components before it checks a database and shows a result without taking any info from a database and second time after it received a result from a database, which creates UI problem of blinking*

*in my example (...removed...) I show it. Once at least one task added refresh the page and the "Add Task!" red block will be visible for the first half a second.

How to fix that issue? Should I use "promise" or there is anything else I can do to show a result only after it checks a database?

Answer Source

Your container subscribes to data and monitors the subscription's ready state:

createContainer(() => {
  const todosHandle = Meteor.subscribe('tasks');
  const loading = !todosHandle.ready();

  return {
    tasks: Tasks.find({}, { sort: { createdAt: -1 } }).fetch(),
}, App);

This means that you component will receive a boolean loading prop which indicates whether or not the data is available. You can use it in your component to render a loading view while the data is loading:

class App extends Component {
  render() {
    const {loading, tasks} = this.props;
    if (loading) {
      return (
        <div className="spinner">
    return (
      <div className="container">
          <h1>Todo List</h1>

or any other combination of components that depends on the loading state.

BTW, the tasks prop is an array, so using tasks.length instead of Object.keys is likely better.