Quantcast
Channel: Active questions tagged react-native+typescript - Stack Overflow
Viewing all articles
Browse latest Browse all 6290

setState (array) entries are disappearing

$
0
0

In the following example, User2's messages are getting erased from the state as soon as the User1 sends a message.

User1 sends a message, it gets displayed on screen. As soon as User2 replies, User1's messages disappear.

I'm persuaded it's a React setState mistake but I've followed the react-native-chat-ui's docs as much as possible but somehow there is something going wrong and I cannot put my finger on it.

Here's a video of the bug in action: https://streamable.com/rxbx18

Thank you.

import React, { useEffect, useState } from 'react';import { Chat, MessageType } from '@flyerhq/react-native-chat-ui'import { SafeAreaProvider } from 'react-native-safe-area-context'const uuidv4 = () => {  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {    const r = Math.floor(Math.random() * 16)    const v = c === 'x' ? r : (r % 4) + 8    return v.toString(16)  })};const user    = { id: uuidv4(), firstName: 'User1' };const chatbot = { id: uuidv4(), firstName: 'User2' };const App = () => {  const [messages, setMessages] = useState<MessageType.Any[]>([])  const addMessage = (message: MessageType.Any) => {    setMessages([message, ...messages]);  };  const handleSendPress = (message: MessageType.PartialText) => {    // display user message    const textMessage: MessageType.Text = {      author   : user,      createdAt: Date.now(),      id       : uuidv4(),      text     : message.text,      type     : 'text',    };    addMessage(textMessage);    // display bot message    // NOTE: adding a timeout so that you can see user's message for a second...    setTimeout(() => {      const chatbotTextMessage: MessageType.Text = {        author   : chatbot,        createdAt: Date.now(),        id       : uuidv4(),        text     : `Response that will erase user's messages...`,        type     : 'text',      };      addMessage(chatbotTextMessage);    }, 1000);  };  return (<SafeAreaProvider><Chat      messages={messages}      showUserNames={true}      onSendPress={handleSendPress}      user={user}    /></SafeAreaProvider>  );}export default App;

Viewing all articles
Browse latest Browse all 6290

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>