Search code examples
reactjsreact-nativereact-native-gifted-chat

What is _id in gifted chat?


Here i am trying to understand the code available in https://www.npmjs.com/package/react-native-gifted-chat this link. But here i am unable to understand why they use 2 _id's (messages:[{_id:1, //code user:{ _id:2, //code }]) in setState function and they are writing 1 id (_id: 1) in render() method. And also what is the difference between id 1 and 2 passed in setState function and id given in render() method.

Here the snippet of code below:

import React from 'react' import { GiftedChat } from 'react-native-gifted-chat'

class Example extends React.Component {
  state = {
    messages: [],
  }

  componentDidMount() {
    this.setState({
      messages: [
        {
          _id: 1,
          text: 'Hello developer',
          createdAt: new Date(),
          user: {
            _id: 2,
            name: 'React Native',
            avatar: 'https://placeimg.com/140/140/any',
          },
        },
      ],
    })
  }

  onSend(messages = []) {
    this.setState(previousState => ({
      messages: GiftedChat.append(previousState.messages, messages),
    }))
  }

  render() {
    return (
      <GiftedChat
        messages={this.state.messages}
        onSend={messages => this.onSend(messages)}
        user={{
          _id: 1,
        }}
      />
    )
  }
}

Solution

  • _id: 1 is id of the message, and _id: 2 is the id of the user that wrote the message, this way the GiftedChat will be able to bind the message with who wrote it.

    With similar logic every message sent by user will be bind with the id in render function.