skip to Main Content

I have a RN app that has a home screen with different chats. When the user taps on a chat, it’s messages are loaded from the local db and displayed. Like Whatsapp does, I want to preload messages and scroll to the last message before the screen is actually loaded. I have tried loading messages in useEffect with an empty dependency array but the messages are shown after the screen is loaded. So the user sees a glitch. I want to avoid that glitch. I have also tried to use useFocusEffect with no effect.

2

Answers


  1. the way that I solved a similar problem, when I had it, was:

    import { ActivityIndicator } from 'react-native';
    import React, { useEffect, useState } from 'react';
    Import { getData } from '// other folder'; // it is the fetching function
      const [isLoading, setIsLoading] = useState(true);
      const [hook, setHook] = useState([]);
    
      useEffect(() => {
        async function fetchData() {
          const response = await getData(key); 
          if (response) {
          setHook(treatedResponse)
          setIsLoading(false);
          }
        }
        fetchData();
      }, []);
    
      if (isLoading || !Hook) {
        return (
          <View style={unifiedStyles.container}>
            <ActivityIndicator />
             {/*loading screen*/}
          </View>
        );
      }else{
        return(
         {/* Normal screen*/}
        )
      }
    

    Put it simply. You have 2 screens. One for the loading and another that only appears when you finish loading everything.
    Keep in mind this is a very simple approach using only useEffect and useState. There are, probably, more optimized ways to go about it.

    Login or Signup to reply.
  2. Try settimeout with useffect hook and loading usestate

    import React, { useState, useEffect } from 'react';
    import { View, Text, FlatList, InteractionManager } from 'react-native';
    
    function ChatScreen({ route }) {
      const [messages, setMessages] = useState([]);
      const [loading, setLoading] = useState(true);
    
      useEffect(() => {
        InteractionManager.runAfterInteractions(() => {
           setTimeout(() => {
            const fetchedMessages = [
             //use your code here  
            ];
            setMessages(fetchedMessages);
            setLoading(false);
          }, 1000);
        });
      }, []);
    
      if (loading) {
        return (
          <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
            <Text>Loading...</Text>
          </View>
        );
      }
    
      return (
        <FlatList
          data={messages}
          renderItem={({ item }) => <Text>{item.text}</Text>}
          keyExtractor={(item) => item.id.toString()}
          inverted // This will start the list from the bottom, like most chat apps
        />
      );
    }
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search