3

I want to edit a message, but it's only updated when i changed this message _id. Can someone provide me how to do it, here is my code:

const onSend = useCallback((messagesToSend = []) => {
        if(editMessage != null){
            setEditMessage()
            const m = messagesToSend[0]
            const newMessages = [...messages]
            const index = newMessages.findIndex(mes => mes._id === editMessage._id);
            console.log('index: ', index)
            if(index > -1){
                newMessages[index].text = m.text // => ***i only edit the text***
                // newMessages[index]._id = uuid.v4() => ***this working if changed _id***
                console.log('newMessages', newMessages[index]) //  => ***new message changed it's text but the bubble not change when re-render***
                LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut)
                setMessage(newMessages)
            }
        }else{
            setReplyMessage()
            appendMessage(messagesToSend)
        }
    })

Julian K
  • 1,877
  • 2
  • 19
  • 27
famfamfam
  • 396
  • 3
  • 8
  • 31

2 Answers2

1

It looks like you're using useCallback without a dependency array. This means that any dependencies that you rely on will be memoized and won't update when you run the function.

You should add messages, editMessage, and maybe setMessage and appendMessage, to the dependency array. Like so:

const onSend = useCallback(
(messageToSend = []) => etc,
[messages, editMessage, setMessage, appendMessage]);

That's the first thing I would try

Julian K
  • 1,877
  • 2
  • 19
  • 27
0

ok i found problem, in MessageText the function componentShouldUpdate need modify a bit

famfamfam
  • 396
  • 3
  • 8
  • 31
  • 1
    that makes sense. For what it's worth, sometimes componentShouldUpdate can make a component slower, depending on the component type. Here's a blog with some info: https://jamesknelson.com/should-i-use-shouldcomponentupdate/ – Julian K Jul 08 '22 at 05:30