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

React useState() - adding new element in array not working

$
0
0

I am making chat app using React native and socket.io but when I receive a message I want to add to array of messages. But somehow its not working. It replaces the array elements instead of pushing/adding element to it.

const [messages, setMessages] = useState([])useEffect(() => {    const id = data.id    receiveMessage(id)}, []);async function receiveMessage(id){    await message.init(id)    message.recieveMessage(message=>{        setMessages([...messages, message])//something is wrong over here    })}async function send(){    if(text){        message.sendMessage(text, data=>{            setMessages([...messages, data])//this part works perfectly        })    }    setText(null)}

here is Messages object:

export class Message {    private socket: Socket    private room: string    constructor(socketio: Socket){        this.socket = socketio        this.room = null    }    async init(id: string){        if(id === this.room) {            return        }        this.room = id        this.socket.emit("join", {id: id, session: await getSessionToken()})        const prom = new Promise((res, rej)=>{            this.socket.on("joined", message=>{                res("done")            })        })        await prom        return "done"    }    public sendMessage(message: string, callback){        const socket = this.socket        socket.emit("message", message)        socket.on("sent", callback)    }    public recieveMessage(callback){        const socket = this.socket        socket.on("receive message", callback)    }}

Viewing all articles
Browse latest Browse all 6287

Trending Articles



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