0

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,
        }}
      />
    )
  }
}
Jeet Mehta
  • 25
  • 5

1 Answers1

0

_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.

B. Mohammad
  • 2,152
  • 1
  • 13
  • 28
  • if this is the case then what is _id:1 written in the return() statement and how it differs from return() statement _id and _id in user block in setState() – Jeet Mehta Mar 06 '20 at 11:45
  • the one in return is the id of the user of the device, for example your user will login to the app, then you will get his id from database and then you use this id in the return function to send new message to database – B. Mohammad Mar 06 '20 at 11:51