What is the best way to render multiple Flatlists using a map function in React Native?

I am facing a puzzling issue that I can't quite grasp.

My goal is to exhibit messages stored in an array using multiple flatlists and then categorize them by date.

These messages are essentially a series of chat conversations containing questions and answers, recorded in an offline database (PouchDB). What I aim to achieve is to showcase the questions that the user has answered and essentially view the conversation logs.

Below is the code snippet:

const screen = Dimensions.get('screen');
const styles = StyleSheet.create({
  logsView: {
    backgroundColor: '#dddddd',
    paddingLeft: 15,
    paddingRight: 2,
    height: '100%',
  },
  dateContainer: {
    width: '75%',
    padding: 1,
    marginTop: 5,
  },
  dateContent: {
    textAlign: 'center',
  },

});

export default class ComponentPlanDetailsScreen
  extends ComeoMeAbstractScreen<PropsType, StateType> {
  static navigationOptions = {
    title: µte('MyPlans'),
    headerRight: (<View />),
  };


  constructor(props: PropsType) {
    super(props);
    this.IfeelMessagesBusiness = new IfeelMessagesBusiness();
    this.state = {
      currentDate: new Date(),
      markedDate: moment(new Date()).format('YYYY-MM-DD'),
      messages: [],
    };
  }
  componentDidMount = () => {
    // Get all messages from chat history
    this.IfeelMessagesBusiness.getAllIfeelMessages().then((result: Object) => {
      this.setState({ messages: result });
    });
  };

    // Render each item of Flatlist
    renderLogItem = ({ item }: Object) => {
      console.log(`je passe renderlogitem ${JSON.stringify(item)}`);
      return <LogItem message={item} />;
    }
    // Key for data in FlatList component
    keyExtractor = (item: Object, index: number): string => index.toString();

    render() {
      const test = [
        {
          stringValue: 'Did you take some drugs ?',
          isImage: false,
          isQuestion: true,
          questionNumber: 6,
          author: {
            id: 1,
            avatar: 'http://image.noelshack.com/fichiers/2016/47/1480031586-1474755093-risitas721.png',
            username: 'Dr Risitas',
          },
          loggedDateTime: '1552033946989',
        },
      ];
      const today = this.state.currentDate;
      const day = moment(today).format('x');
      return (
        <View>
          <Carousel
            animate={false}
            indicatorSize={10}
            height={screen.height * 0.7
            }
          >
            <View>
              <ScrollView
                style={styles.logsView}
              >
                <View>
                  {this.state.messages.map((ItemListByDate: Object): Array<Object> => {
                  console.log(`je passe array ${JSON.stringify([ItemListByDate])}`);

                    return (

                      <View key={ItemListByDate.loggedDateTime.toString()}>
                        <View style={styles.dateContainer}>
                          { (parseInt(ItemListByDate.loggedDateTime, 10) + 172800000) <= parseInt(day.toString(), 10) ?
                            <Text style={styles.dateContent}>{moment(parseInt(ItemListByDate.loggedDateTime, 10)).format('DD-MM-YYYY')}</Text>

                          :

                            <Text style={styles.dateContent}>{moment(parseInt(ItemListByDate.loggedDateTime, 10)).fromNow()}</Text>
                         }
                        </View>
                        <View>
                          <FlatList
                            data={[ItemListByDate]}
                            renderItem={this.renderLogItem}
                            keyExtractor={this.keyExtractor}
                            ref={(ref: any) => { this.flatList = ref; }}
                            onContentSizeChange={(): any => this.flatList.scrollToEnd({ animated: true })}
                            onLayout={(): any => this.flatList.scrollToEnd({ animated: true })}
                          />
                        </View>
                      </View>);
                    })
                  }
                </View>
              </ScrollView>
            </View>
          </Carousel>
        </View>
      );
    }
}

The challenge I'm encountering lies in the fact that the renderLogItem function which should invoke the LogItem component is not being executed, even though the ItemListByDate array is displayed in the log. Instead of showing the expected messages, only the gray background of the ScrollView component is visible.

However, when I substitute `test` array for `this.state.messages` within the map function, the message displays correctly on the interface and renderLogItem is called as expected.

It seems like the initial state of messages being empty might be causing a visual glitch where the messages remain hidden until a re-render occurs triggered by the update of the state in componentDidMount.

Your insights and assistance on resolving this matter would be greatly appreciated!

Answer №1

One possible explanation could be related to the asynchronous nature of

this.IfeelMessagesBusiness.getAllIfeelMessages()
. This may cause the render method to initially attempt mapping over undefined values, leading to a lack of updates.

Have you considered using a different approach such as implementing a FlatList instead?

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Adjusting the position of a stationary element when the page is unresponsive and scrolling

Managing a large web page with extensive JavaScript functionality can be challenging, especially when dealing with fixed position elements that update based on user scroll behavior. A common issue that arises is the noticeable jumping of these elements whe ...

Axios Instance class request cancellation

In my Redux-saga project, I am working on implementing a polling function where I need to make a request every second. If there is no response from the endpoint, I want to cancel the previous request and initiate a new one using Axios client. I have organi ...

What is the reason behind the trigger event failing to invoke events that are specified with addEventListener?

I have created a sample scenario: http://jsfiddle.net/y42pu5b6/ $(function(){ function ping (){ alert( "function fired" ); console.log("fired"); } console.log($("input#one")[0]); $("input#one")[0].addEventListener("chan ...

Typescript mapping data structure

Currently, I am facing the challenge of mapping complex models. My data consists of an array of Carts with attributes such as id and name. In addition, there is a dictionary where each key represents a type and its corresponding value includes different p ...

Image displayed in a graphic container

When dynamically creating a ScrollView and TableLayout, I ran into a problem. How can I incorporate my graphics using Canvas into an ImageView? Canvas canvas = new Canvas(); ... canvas.DrawPath(path, paint); ImageView imageView = new ImageView(this); ...

Tips for evaluating the build size of a Create React App and ways to minimize it

Currently, I've been following the steps outlined in this helpful guide: https://create-react-app.dev/docs/analyzing-the-bundle-size/ and I'm gearing up to execute the analyze command to assess my app's size. Is this approach the most effect ...

The ultimate guide to leveraging UIApplication handleOpenURL Notifications

I've been attempting to manage UIApplication Notifications in order to retrieve URL Schemes within the current open view. Despite trying a variety of notifications, I'm unsure of which object actually contains the URL Schemes. NSNotificationCen ...

What is the best way to save a webpage when a user clicks a button before leaving the page with Javascript

I've exhausted all my options in trying to find a way to trigger a button that saves the page upon exit, but it never seems to work. I need the event to occur even if the button is not visible at the time of the page exit. The new security protocols o ...

When parsing JSON files, the focus is on extracting the object name rather than

I have a JSON file that I created and stored at this link: I have added this file to my project and am attempting to parse it. Strangely, when I use NSLog to output the result, it just displays "statement" instead of the statement object. I was expecting ...

Update the background URL of a div element using an HTML tag

My question is about a CSS div with set dimensions and background that I want to change on hover. I am aware that this seems like a simple task, but what I really want to do is retrieve the background sources from within the HTML tag itself. For example: ...

How can I validate a password input in a form on click and reveal a hidden div on the same page without refreshing?

I've been attempting to create a password-only form that reveals a hidden div on the same page when the correct password is entered. I want to avoid reloading the page, but I'm unsure of how to achieve this. function checkPassword() { var co ...

Utilizing Rails for dynamic form validation with AJAX

As someone who is new to jQuery, AJAX, and JavaScript in general, I am facing a challenge with front-end validation for a Rails form that utilizes an ajax call to query the server. The validation works fine when I am debugging, giving enough time for the A ...

Revising Global Variables and States in React

Recently delving into React and tackling a project. I find myself needing to manage a counter as a global variable and modify its value within a component. I initialized this counter using the useState hook as const [currentMaxRow, setRow] = useState(3) ...

Leveraging jsonp with nodejs and original ajax

I wanted to understand how jsonp works, so I decided to create a demo using nodejs without jQuery. However, I encountered some issues with my code. Here is what I tried: views/index.jade doctype html html head title Demo of jsonp body #res ...

Tips on concealing an image within a second

Can anyone assist me with hiding an image right after a flip animation ends, within one second? ...

Tips for isolating the month values from the res.body.results array of objects with the help of JS Array map()

Looking to adjust the custom code that I have which aims to extract months from a string using regex. It seems like I'm almost there but not quite hitting the mark. When checking the console log, I am getting "undefined" values for key/value pairs and ...

In NextJS 12, an UnhandledPromiseRejectionWarning occurs when trying to reference the TextEncoder which is not defined

Currently, I am working on developing a Spotify clone using NextJS 12 along with a Tailwind CSS template. To initiate the project, I executed the following command: npx create-next-app -e with-tailwindcss spotify-2. The project was successfully created, b ...

Error: The value is null and cannot be read

My external application is set up within a const called setupRemote, where it starts with the appConfig in the variable allowAppInstance. export const setupRemote = () => { if (isRemoteAvailable) { try { ... const allowAppInstance = S ...

Google Cloud Messaging (GCM) sends notifications displaying JSON messages

I'm currently struggling with creating GCM notifications. The default behavior is to display the message in JSON format. What I want to do is wrap my JSON data and only show a simple message like 'You have a new notification' in the notific ...

Using xignite api to retrieve stock data

I've been encountering difficulties trying to make this JavaScript script function properly. Every time I attempt to run it, I receive an error message stating: "XMLHttpRequest cannot load" "No 'Access-Control-Allow-Origin' header is presen ...