Having Trouble Loading Earlier Messages in React-native GiftedChat Chat App with Firebase












2














I have been working on a chat app using Gifted-Chat and a Firebase RealTime database (and running it with Expo). At this point, the basic messaging works, but I am trying to enable to app to load earlier messages when the user scrolls up and hits the button that appears (I am aware of the GiftedChat prop for this). Unfortunately, I have been having trouble doing this and am a bit stumped.



There are two separate problems I have been running up against that I am aware of.




  1. Clicking the loadEarlier button gives me an undefined is not a function (near '...this.setState...' runtime error (clearly, something is wrong with the skeleton function I put there).

  2. The bigger issues is that I am still not clear on how to download the n number of messages before the oldest messages currently loaded. I have looked at the GiftedChat example and this post for help, but must confess that I am still lost (the best I can figure is that I need to sort the messages, possibly by timestamp, somehow get the right range, then parse them and prepend them to the messages array in state, but I cannot figure out how to do this, especially the later parts).


The relevant parts of the code for my chat screen are below, as is a screenshot of the structure of my firebase database. I would appreciate any help regarding both of these issues.



// Your run of the mill React-Native imports.
import React, { Component } from 'react';
import { ActivityIndicator, StyleSheet, Text, View } from 'react-native';
import * as firebase from 'firebase';
// Our custom components.
import { Input } from '../components/Input';
import { Button } from '../components/Button';
import { BotButton } from '../components/BotButton';
// Array of potential bot responses. Might be a fancy schmancy Markov
// chain like thing in the future.
import {botResponses} from '../Constants.js';
// Gifted-chat import. The library takes care of fun stuff like
// rendering message bubbles and having a message composer.
import { GiftedChat } from 'react-native-gifted-chat';
// To keep keyboard from covering up text input.
import { KeyboardAvoidingView } from 'react-native';
// Because keyboard avoiding behavior is platform specific.
import {Platform} from 'react-native';

console.disableYellowBox = true;

class Chat extends Component {
state = {
messages: ,
isLoadingEarlier: false,
};

// Reference to where in Firebase DB messages will be stored.
get ref() {
return firebase.database().ref('messages');
}

onLoadEarlier() {
this.setState((previousState) => {
return {
isLoadingEarlier: true,
};
});
console.log(this.state.isLoadingEarlier)
this.setState((previousState) => {
return {
isLoadingEarlier: false,
};
});
}

// Get last 20 messages, any incoming messages, and send them to parse.
on = callback =>
this.ref
.limitToLast(20)
.on('child_added', snapshot => callback(this.parse(snapshot)));
parse = snapshot => {
// Return whatever is associated with snapshot.
const { timestamp: numberStamp, text, user } = snapshot.val();
const { key: _id } = snapshot;
// Convert timestamp to JS date object.
const timestamp = new Date(numberStamp);
// Create object for Gifted Chat. id is unique.
const message = {
_id,
timestamp,
text,
user,
};
return message;
};
// To unsubscribe from database
off() {
this.ref.off();
}

// Helper function to get user UID.
get uid() {
return (firebase.auth().currentUser || {}).uid;
}
// Get timestamp for saving messages.
get timestamp() {
return firebase.database.ServerValue.TIMESTAMP;
}

// Helper function that takes array of messages and prepares all of
// them to be sent.
send = messages => {
for (let i = 0; i < messages.length; i++) {
const { text, user } = messages[i];
const message = {
text,
user,
timestamp: this.timestamp,
};
this.append(message);
}
};

// Save message objects. Actually sends them to server.
append = message => this.ref.push(message);

// When we open the chat, start looking for messages.
componentDidMount() {
this.on(message =>
this.setState(previousState => ({
messages: GiftedChat.append(previousState.messages, message),
}))
);
}
get user() {
// Return name and UID for GiftedChat to parse
return {
name: this.props.navigation.state.params.name,
_id: this.uid,
};
}
// Unsubscribe when we close the chat screen.
componentWillUnmount() {
this.off();
}

render() {
return (
<View>
<GiftedChat
loadEarlier={true}
onLoadEarlier={this.onLoadEarlier}
isLoadingEarlier={this.state.isLoadingEarlier}
messages={this.state.messages}
onSend={this.send}
user={this.user}
/>
</View>
);
}

}
export default Chat;


Screenshot of DB










share|improve this question





























    2














    I have been working on a chat app using Gifted-Chat and a Firebase RealTime database (and running it with Expo). At this point, the basic messaging works, but I am trying to enable to app to load earlier messages when the user scrolls up and hits the button that appears (I am aware of the GiftedChat prop for this). Unfortunately, I have been having trouble doing this and am a bit stumped.



    There are two separate problems I have been running up against that I am aware of.




    1. Clicking the loadEarlier button gives me an undefined is not a function (near '...this.setState...' runtime error (clearly, something is wrong with the skeleton function I put there).

    2. The bigger issues is that I am still not clear on how to download the n number of messages before the oldest messages currently loaded. I have looked at the GiftedChat example and this post for help, but must confess that I am still lost (the best I can figure is that I need to sort the messages, possibly by timestamp, somehow get the right range, then parse them and prepend them to the messages array in state, but I cannot figure out how to do this, especially the later parts).


    The relevant parts of the code for my chat screen are below, as is a screenshot of the structure of my firebase database. I would appreciate any help regarding both of these issues.



    // Your run of the mill React-Native imports.
    import React, { Component } from 'react';
    import { ActivityIndicator, StyleSheet, Text, View } from 'react-native';
    import * as firebase from 'firebase';
    // Our custom components.
    import { Input } from '../components/Input';
    import { Button } from '../components/Button';
    import { BotButton } from '../components/BotButton';
    // Array of potential bot responses. Might be a fancy schmancy Markov
    // chain like thing in the future.
    import {botResponses} from '../Constants.js';
    // Gifted-chat import. The library takes care of fun stuff like
    // rendering message bubbles and having a message composer.
    import { GiftedChat } from 'react-native-gifted-chat';
    // To keep keyboard from covering up text input.
    import { KeyboardAvoidingView } from 'react-native';
    // Because keyboard avoiding behavior is platform specific.
    import {Platform} from 'react-native';

    console.disableYellowBox = true;

    class Chat extends Component {
    state = {
    messages: ,
    isLoadingEarlier: false,
    };

    // Reference to where in Firebase DB messages will be stored.
    get ref() {
    return firebase.database().ref('messages');
    }

    onLoadEarlier() {
    this.setState((previousState) => {
    return {
    isLoadingEarlier: true,
    };
    });
    console.log(this.state.isLoadingEarlier)
    this.setState((previousState) => {
    return {
    isLoadingEarlier: false,
    };
    });
    }

    // Get last 20 messages, any incoming messages, and send them to parse.
    on = callback =>
    this.ref
    .limitToLast(20)
    .on('child_added', snapshot => callback(this.parse(snapshot)));
    parse = snapshot => {
    // Return whatever is associated with snapshot.
    const { timestamp: numberStamp, text, user } = snapshot.val();
    const { key: _id } = snapshot;
    // Convert timestamp to JS date object.
    const timestamp = new Date(numberStamp);
    // Create object for Gifted Chat. id is unique.
    const message = {
    _id,
    timestamp,
    text,
    user,
    };
    return message;
    };
    // To unsubscribe from database
    off() {
    this.ref.off();
    }

    // Helper function to get user UID.
    get uid() {
    return (firebase.auth().currentUser || {}).uid;
    }
    // Get timestamp for saving messages.
    get timestamp() {
    return firebase.database.ServerValue.TIMESTAMP;
    }

    // Helper function that takes array of messages and prepares all of
    // them to be sent.
    send = messages => {
    for (let i = 0; i < messages.length; i++) {
    const { text, user } = messages[i];
    const message = {
    text,
    user,
    timestamp: this.timestamp,
    };
    this.append(message);
    }
    };

    // Save message objects. Actually sends them to server.
    append = message => this.ref.push(message);

    // When we open the chat, start looking for messages.
    componentDidMount() {
    this.on(message =>
    this.setState(previousState => ({
    messages: GiftedChat.append(previousState.messages, message),
    }))
    );
    }
    get user() {
    // Return name and UID for GiftedChat to parse
    return {
    name: this.props.navigation.state.params.name,
    _id: this.uid,
    };
    }
    // Unsubscribe when we close the chat screen.
    componentWillUnmount() {
    this.off();
    }

    render() {
    return (
    <View>
    <GiftedChat
    loadEarlier={true}
    onLoadEarlier={this.onLoadEarlier}
    isLoadingEarlier={this.state.isLoadingEarlier}
    messages={this.state.messages}
    onSend={this.send}
    user={this.user}
    />
    </View>
    );
    }

    }
    export default Chat;


    Screenshot of DB










    share|improve this question



























      2












      2








      2


      0





      I have been working on a chat app using Gifted-Chat and a Firebase RealTime database (and running it with Expo). At this point, the basic messaging works, but I am trying to enable to app to load earlier messages when the user scrolls up and hits the button that appears (I am aware of the GiftedChat prop for this). Unfortunately, I have been having trouble doing this and am a bit stumped.



      There are two separate problems I have been running up against that I am aware of.




      1. Clicking the loadEarlier button gives me an undefined is not a function (near '...this.setState...' runtime error (clearly, something is wrong with the skeleton function I put there).

      2. The bigger issues is that I am still not clear on how to download the n number of messages before the oldest messages currently loaded. I have looked at the GiftedChat example and this post for help, but must confess that I am still lost (the best I can figure is that I need to sort the messages, possibly by timestamp, somehow get the right range, then parse them and prepend them to the messages array in state, but I cannot figure out how to do this, especially the later parts).


      The relevant parts of the code for my chat screen are below, as is a screenshot of the structure of my firebase database. I would appreciate any help regarding both of these issues.



      // Your run of the mill React-Native imports.
      import React, { Component } from 'react';
      import { ActivityIndicator, StyleSheet, Text, View } from 'react-native';
      import * as firebase from 'firebase';
      // Our custom components.
      import { Input } from '../components/Input';
      import { Button } from '../components/Button';
      import { BotButton } from '../components/BotButton';
      // Array of potential bot responses. Might be a fancy schmancy Markov
      // chain like thing in the future.
      import {botResponses} from '../Constants.js';
      // Gifted-chat import. The library takes care of fun stuff like
      // rendering message bubbles and having a message composer.
      import { GiftedChat } from 'react-native-gifted-chat';
      // To keep keyboard from covering up text input.
      import { KeyboardAvoidingView } from 'react-native';
      // Because keyboard avoiding behavior is platform specific.
      import {Platform} from 'react-native';

      console.disableYellowBox = true;

      class Chat extends Component {
      state = {
      messages: ,
      isLoadingEarlier: false,
      };

      // Reference to where in Firebase DB messages will be stored.
      get ref() {
      return firebase.database().ref('messages');
      }

      onLoadEarlier() {
      this.setState((previousState) => {
      return {
      isLoadingEarlier: true,
      };
      });
      console.log(this.state.isLoadingEarlier)
      this.setState((previousState) => {
      return {
      isLoadingEarlier: false,
      };
      });
      }

      // Get last 20 messages, any incoming messages, and send them to parse.
      on = callback =>
      this.ref
      .limitToLast(20)
      .on('child_added', snapshot => callback(this.parse(snapshot)));
      parse = snapshot => {
      // Return whatever is associated with snapshot.
      const { timestamp: numberStamp, text, user } = snapshot.val();
      const { key: _id } = snapshot;
      // Convert timestamp to JS date object.
      const timestamp = new Date(numberStamp);
      // Create object for Gifted Chat. id is unique.
      const message = {
      _id,
      timestamp,
      text,
      user,
      };
      return message;
      };
      // To unsubscribe from database
      off() {
      this.ref.off();
      }

      // Helper function to get user UID.
      get uid() {
      return (firebase.auth().currentUser || {}).uid;
      }
      // Get timestamp for saving messages.
      get timestamp() {
      return firebase.database.ServerValue.TIMESTAMP;
      }

      // Helper function that takes array of messages and prepares all of
      // them to be sent.
      send = messages => {
      for (let i = 0; i < messages.length; i++) {
      const { text, user } = messages[i];
      const message = {
      text,
      user,
      timestamp: this.timestamp,
      };
      this.append(message);
      }
      };

      // Save message objects. Actually sends them to server.
      append = message => this.ref.push(message);

      // When we open the chat, start looking for messages.
      componentDidMount() {
      this.on(message =>
      this.setState(previousState => ({
      messages: GiftedChat.append(previousState.messages, message),
      }))
      );
      }
      get user() {
      // Return name and UID for GiftedChat to parse
      return {
      name: this.props.navigation.state.params.name,
      _id: this.uid,
      };
      }
      // Unsubscribe when we close the chat screen.
      componentWillUnmount() {
      this.off();
      }

      render() {
      return (
      <View>
      <GiftedChat
      loadEarlier={true}
      onLoadEarlier={this.onLoadEarlier}
      isLoadingEarlier={this.state.isLoadingEarlier}
      messages={this.state.messages}
      onSend={this.send}
      user={this.user}
      />
      </View>
      );
      }

      }
      export default Chat;


      Screenshot of DB










      share|improve this question















      I have been working on a chat app using Gifted-Chat and a Firebase RealTime database (and running it with Expo). At this point, the basic messaging works, but I am trying to enable to app to load earlier messages when the user scrolls up and hits the button that appears (I am aware of the GiftedChat prop for this). Unfortunately, I have been having trouble doing this and am a bit stumped.



      There are two separate problems I have been running up against that I am aware of.




      1. Clicking the loadEarlier button gives me an undefined is not a function (near '...this.setState...' runtime error (clearly, something is wrong with the skeleton function I put there).

      2. The bigger issues is that I am still not clear on how to download the n number of messages before the oldest messages currently loaded. I have looked at the GiftedChat example and this post for help, but must confess that I am still lost (the best I can figure is that I need to sort the messages, possibly by timestamp, somehow get the right range, then parse them and prepend them to the messages array in state, but I cannot figure out how to do this, especially the later parts).


      The relevant parts of the code for my chat screen are below, as is a screenshot of the structure of my firebase database. I would appreciate any help regarding both of these issues.



      // Your run of the mill React-Native imports.
      import React, { Component } from 'react';
      import { ActivityIndicator, StyleSheet, Text, View } from 'react-native';
      import * as firebase from 'firebase';
      // Our custom components.
      import { Input } from '../components/Input';
      import { Button } from '../components/Button';
      import { BotButton } from '../components/BotButton';
      // Array of potential bot responses. Might be a fancy schmancy Markov
      // chain like thing in the future.
      import {botResponses} from '../Constants.js';
      // Gifted-chat import. The library takes care of fun stuff like
      // rendering message bubbles and having a message composer.
      import { GiftedChat } from 'react-native-gifted-chat';
      // To keep keyboard from covering up text input.
      import { KeyboardAvoidingView } from 'react-native';
      // Because keyboard avoiding behavior is platform specific.
      import {Platform} from 'react-native';

      console.disableYellowBox = true;

      class Chat extends Component {
      state = {
      messages: ,
      isLoadingEarlier: false,
      };

      // Reference to where in Firebase DB messages will be stored.
      get ref() {
      return firebase.database().ref('messages');
      }

      onLoadEarlier() {
      this.setState((previousState) => {
      return {
      isLoadingEarlier: true,
      };
      });
      console.log(this.state.isLoadingEarlier)
      this.setState((previousState) => {
      return {
      isLoadingEarlier: false,
      };
      });
      }

      // Get last 20 messages, any incoming messages, and send them to parse.
      on = callback =>
      this.ref
      .limitToLast(20)
      .on('child_added', snapshot => callback(this.parse(snapshot)));
      parse = snapshot => {
      // Return whatever is associated with snapshot.
      const { timestamp: numberStamp, text, user } = snapshot.val();
      const { key: _id } = snapshot;
      // Convert timestamp to JS date object.
      const timestamp = new Date(numberStamp);
      // Create object for Gifted Chat. id is unique.
      const message = {
      _id,
      timestamp,
      text,
      user,
      };
      return message;
      };
      // To unsubscribe from database
      off() {
      this.ref.off();
      }

      // Helper function to get user UID.
      get uid() {
      return (firebase.auth().currentUser || {}).uid;
      }
      // Get timestamp for saving messages.
      get timestamp() {
      return firebase.database.ServerValue.TIMESTAMP;
      }

      // Helper function that takes array of messages and prepares all of
      // them to be sent.
      send = messages => {
      for (let i = 0; i < messages.length; i++) {
      const { text, user } = messages[i];
      const message = {
      text,
      user,
      timestamp: this.timestamp,
      };
      this.append(message);
      }
      };

      // Save message objects. Actually sends them to server.
      append = message => this.ref.push(message);

      // When we open the chat, start looking for messages.
      componentDidMount() {
      this.on(message =>
      this.setState(previousState => ({
      messages: GiftedChat.append(previousState.messages, message),
      }))
      );
      }
      get user() {
      // Return name and UID for GiftedChat to parse
      return {
      name: this.props.navigation.state.params.name,
      _id: this.uid,
      };
      }
      // Unsubscribe when we close the chat screen.
      componentWillUnmount() {
      this.off();
      }

      render() {
      return (
      <View>
      <GiftedChat
      loadEarlier={true}
      onLoadEarlier={this.onLoadEarlier}
      isLoadingEarlier={this.state.isLoadingEarlier}
      messages={this.state.messages}
      onSend={this.send}
      user={this.user}
      />
      </View>
      );
      }

      }
      export default Chat;


      Screenshot of DB







      javascript firebase react-native firebase-realtime-database react-native-gifted-chat






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Dec 28 '18 at 6:09









      Frank van Puffelen

      227k28373396




      227k28373396










      asked Dec 28 '18 at 0:06









      Fake Name

      3701314




      3701314
























          1 Answer
          1






          active

          oldest

          votes


















          1














          For your first issue, you should declare your onLoadEarlier with => function so as to get the current instance this i.e. your code should look like below:



          onLoadEarlier = () => {
          this.setState((previousState) => {
          return {
          isLoadingEarlier: true,
          };
          }, () => {
          console.log(this.state.isLoadingEarlier)
          this.setState((previousState) => {
          return {
          isLoadingEarlier: false,
          };
          });
          });
          }


          Also, setState is asynchronous in nature, so you should rather depend on the second parameter of the setState i.e. the callback to ensure that the next lines of code execute synchronously.



          Lastly, if you are using class syntax then you should declare the state in constructor like below:



          class Chat extends Component {
          constructor (props) {
          super (props);
          state = {
          messages: ,
          isLoadingEarlier: false,
          };
          }
          ......

          onLoadEarlier = () => {
          this.setState((previousState) => {
          return {
          isLoadingEarlier: true,
          };
          }, () => {
          console.log(this.state.isLoadingEarlier)
          this.setState((previousState) => {
          return {
          isLoadingEarlier: false,
          };
          });
          });
          }
          ...
          }


          For your second answer, I will update the answer in sometime to help with that.



          Hope this helps. Happy Coding :)






          share|improve this answer





















          • Thank you, this all works. I am still pretty new to React-native (first project), so am wondering why I should declare state in the constructor?
            – Fake Name
            Dec 28 '18 at 21:32










          • This might help you understand how the class members are defined and declared.
            – Suraj Malviya
            Dec 29 '18 at 6:54










          • Thank you, I did not realize how complex javascript is. After going through the page though, I am still confused as to why a constructor needs to be used to declare state, given that the code works for me after applying your first fixes without adding a constructor.
            – Fake Name
            Dec 29 '18 at 23:47










          • Sorry, never mind, I think that I finally mostly understand the whole binding thing. If you get a chance to look into how to load older messages though, I would really appreciate it.
            – Fake Name
            Dec 31 '18 at 0:08











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53952225%2fhaving-trouble-loading-earlier-messages-in-react-native-giftedchat-chat-app-with%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          1














          For your first issue, you should declare your onLoadEarlier with => function so as to get the current instance this i.e. your code should look like below:



          onLoadEarlier = () => {
          this.setState((previousState) => {
          return {
          isLoadingEarlier: true,
          };
          }, () => {
          console.log(this.state.isLoadingEarlier)
          this.setState((previousState) => {
          return {
          isLoadingEarlier: false,
          };
          });
          });
          }


          Also, setState is asynchronous in nature, so you should rather depend on the second parameter of the setState i.e. the callback to ensure that the next lines of code execute synchronously.



          Lastly, if you are using class syntax then you should declare the state in constructor like below:



          class Chat extends Component {
          constructor (props) {
          super (props);
          state = {
          messages: ,
          isLoadingEarlier: false,
          };
          }
          ......

          onLoadEarlier = () => {
          this.setState((previousState) => {
          return {
          isLoadingEarlier: true,
          };
          }, () => {
          console.log(this.state.isLoadingEarlier)
          this.setState((previousState) => {
          return {
          isLoadingEarlier: false,
          };
          });
          });
          }
          ...
          }


          For your second answer, I will update the answer in sometime to help with that.



          Hope this helps. Happy Coding :)






          share|improve this answer





















          • Thank you, this all works. I am still pretty new to React-native (first project), so am wondering why I should declare state in the constructor?
            – Fake Name
            Dec 28 '18 at 21:32










          • This might help you understand how the class members are defined and declared.
            – Suraj Malviya
            Dec 29 '18 at 6:54










          • Thank you, I did not realize how complex javascript is. After going through the page though, I am still confused as to why a constructor needs to be used to declare state, given that the code works for me after applying your first fixes without adding a constructor.
            – Fake Name
            Dec 29 '18 at 23:47










          • Sorry, never mind, I think that I finally mostly understand the whole binding thing. If you get a chance to look into how to load older messages though, I would really appreciate it.
            – Fake Name
            Dec 31 '18 at 0:08
















          1














          For your first issue, you should declare your onLoadEarlier with => function so as to get the current instance this i.e. your code should look like below:



          onLoadEarlier = () => {
          this.setState((previousState) => {
          return {
          isLoadingEarlier: true,
          };
          }, () => {
          console.log(this.state.isLoadingEarlier)
          this.setState((previousState) => {
          return {
          isLoadingEarlier: false,
          };
          });
          });
          }


          Also, setState is asynchronous in nature, so you should rather depend on the second parameter of the setState i.e. the callback to ensure that the next lines of code execute synchronously.



          Lastly, if you are using class syntax then you should declare the state in constructor like below:



          class Chat extends Component {
          constructor (props) {
          super (props);
          state = {
          messages: ,
          isLoadingEarlier: false,
          };
          }
          ......

          onLoadEarlier = () => {
          this.setState((previousState) => {
          return {
          isLoadingEarlier: true,
          };
          }, () => {
          console.log(this.state.isLoadingEarlier)
          this.setState((previousState) => {
          return {
          isLoadingEarlier: false,
          };
          });
          });
          }
          ...
          }


          For your second answer, I will update the answer in sometime to help with that.



          Hope this helps. Happy Coding :)






          share|improve this answer





















          • Thank you, this all works. I am still pretty new to React-native (first project), so am wondering why I should declare state in the constructor?
            – Fake Name
            Dec 28 '18 at 21:32










          • This might help you understand how the class members are defined and declared.
            – Suraj Malviya
            Dec 29 '18 at 6:54










          • Thank you, I did not realize how complex javascript is. After going through the page though, I am still confused as to why a constructor needs to be used to declare state, given that the code works for me after applying your first fixes without adding a constructor.
            – Fake Name
            Dec 29 '18 at 23:47










          • Sorry, never mind, I think that I finally mostly understand the whole binding thing. If you get a chance to look into how to load older messages though, I would really appreciate it.
            – Fake Name
            Dec 31 '18 at 0:08














          1












          1








          1






          For your first issue, you should declare your onLoadEarlier with => function so as to get the current instance this i.e. your code should look like below:



          onLoadEarlier = () => {
          this.setState((previousState) => {
          return {
          isLoadingEarlier: true,
          };
          }, () => {
          console.log(this.state.isLoadingEarlier)
          this.setState((previousState) => {
          return {
          isLoadingEarlier: false,
          };
          });
          });
          }


          Also, setState is asynchronous in nature, so you should rather depend on the second parameter of the setState i.e. the callback to ensure that the next lines of code execute synchronously.



          Lastly, if you are using class syntax then you should declare the state in constructor like below:



          class Chat extends Component {
          constructor (props) {
          super (props);
          state = {
          messages: ,
          isLoadingEarlier: false,
          };
          }
          ......

          onLoadEarlier = () => {
          this.setState((previousState) => {
          return {
          isLoadingEarlier: true,
          };
          }, () => {
          console.log(this.state.isLoadingEarlier)
          this.setState((previousState) => {
          return {
          isLoadingEarlier: false,
          };
          });
          });
          }
          ...
          }


          For your second answer, I will update the answer in sometime to help with that.



          Hope this helps. Happy Coding :)






          share|improve this answer












          For your first issue, you should declare your onLoadEarlier with => function so as to get the current instance this i.e. your code should look like below:



          onLoadEarlier = () => {
          this.setState((previousState) => {
          return {
          isLoadingEarlier: true,
          };
          }, () => {
          console.log(this.state.isLoadingEarlier)
          this.setState((previousState) => {
          return {
          isLoadingEarlier: false,
          };
          });
          });
          }


          Also, setState is asynchronous in nature, so you should rather depend on the second parameter of the setState i.e. the callback to ensure that the next lines of code execute synchronously.



          Lastly, if you are using class syntax then you should declare the state in constructor like below:



          class Chat extends Component {
          constructor (props) {
          super (props);
          state = {
          messages: ,
          isLoadingEarlier: false,
          };
          }
          ......

          onLoadEarlier = () => {
          this.setState((previousState) => {
          return {
          isLoadingEarlier: true,
          };
          }, () => {
          console.log(this.state.isLoadingEarlier)
          this.setState((previousState) => {
          return {
          isLoadingEarlier: false,
          };
          });
          });
          }
          ...
          }


          For your second answer, I will update the answer in sometime to help with that.



          Hope this helps. Happy Coding :)







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Dec 28 '18 at 6:44









          Suraj Malviya

          803414




          803414












          • Thank you, this all works. I am still pretty new to React-native (first project), so am wondering why I should declare state in the constructor?
            – Fake Name
            Dec 28 '18 at 21:32










          • This might help you understand how the class members are defined and declared.
            – Suraj Malviya
            Dec 29 '18 at 6:54










          • Thank you, I did not realize how complex javascript is. After going through the page though, I am still confused as to why a constructor needs to be used to declare state, given that the code works for me after applying your first fixes without adding a constructor.
            – Fake Name
            Dec 29 '18 at 23:47










          • Sorry, never mind, I think that I finally mostly understand the whole binding thing. If you get a chance to look into how to load older messages though, I would really appreciate it.
            – Fake Name
            Dec 31 '18 at 0:08


















          • Thank you, this all works. I am still pretty new to React-native (first project), so am wondering why I should declare state in the constructor?
            – Fake Name
            Dec 28 '18 at 21:32










          • This might help you understand how the class members are defined and declared.
            – Suraj Malviya
            Dec 29 '18 at 6:54










          • Thank you, I did not realize how complex javascript is. After going through the page though, I am still confused as to why a constructor needs to be used to declare state, given that the code works for me after applying your first fixes without adding a constructor.
            – Fake Name
            Dec 29 '18 at 23:47










          • Sorry, never mind, I think that I finally mostly understand the whole binding thing. If you get a chance to look into how to load older messages though, I would really appreciate it.
            – Fake Name
            Dec 31 '18 at 0:08
















          Thank you, this all works. I am still pretty new to React-native (first project), so am wondering why I should declare state in the constructor?
          – Fake Name
          Dec 28 '18 at 21:32




          Thank you, this all works. I am still pretty new to React-native (first project), so am wondering why I should declare state in the constructor?
          – Fake Name
          Dec 28 '18 at 21:32












          This might help you understand how the class members are defined and declared.
          – Suraj Malviya
          Dec 29 '18 at 6:54




          This might help you understand how the class members are defined and declared.
          – Suraj Malviya
          Dec 29 '18 at 6:54












          Thank you, I did not realize how complex javascript is. After going through the page though, I am still confused as to why a constructor needs to be used to declare state, given that the code works for me after applying your first fixes without adding a constructor.
          – Fake Name
          Dec 29 '18 at 23:47




          Thank you, I did not realize how complex javascript is. After going through the page though, I am still confused as to why a constructor needs to be used to declare state, given that the code works for me after applying your first fixes without adding a constructor.
          – Fake Name
          Dec 29 '18 at 23:47












          Sorry, never mind, I think that I finally mostly understand the whole binding thing. If you get a chance to look into how to load older messages though, I would really appreciate it.
          – Fake Name
          Dec 31 '18 at 0:08




          Sorry, never mind, I think that I finally mostly understand the whole binding thing. If you get a chance to look into how to load older messages though, I would really appreciate it.
          – Fake Name
          Dec 31 '18 at 0:08


















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.





          Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


          Please pay close attention to the following guidance:


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53952225%2fhaving-trouble-loading-earlier-messages-in-react-native-giftedchat-chat-app-with%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Mossoró

          Error while reading .h5 file using the rhdf5 package in R

          Pushsharp Apns notification error: 'InvalidToken'