0

store.js

import {useLocalObservable} from "mobx-react-lite";

function chatStore() {
    return {
        chatmsg: [],
        setChatMsg(arr) {
            this.chatmsg = arr
        },
        addChatMsg(msg) {
            this.chatmsg.push(msg)
        }
    }
}

export const useChatStore = () => useLocalObservable(chatStore)

app.js

    const App = () => {

    const chatMsgStore = useChatStore()

    const AppFunctions = {chatMsgStore}

    useEffect(() => {
        socket.on(activechat.chatid, (bdmsg) => {
            chatMsgStore.addChatMsg(bdmsg)
        })
        return () => {
            socket.off(activechat.chatid)
        }
    }, [activechat, chatMsgStore.chatmsg])

    return (
        <>
           <AppContext.Provider value={AppFunctions}>
                 .....................
           </AppContext.Provider>
        </>
    )
  }

  export default App;

fetch.js

async function getChatMessages(url, body, userStore, chatMsgStore) {
........
            chatMsgStore.setChatMsg(firstResData)
........

on app load i add a socket listener which deps are activechat and chatMsgStore.
this listener is dynamic and must be changed when deps change.
the only purpose of this listener is to add a msg to the store and re-render the observer component

deps :
activechat - non store state
chatMsgStore.chatmsg - store state

why chatMsgStore.addChatMsg(bdmsg) does not effect the store? so deeply nested components inside App.js is not re-rendering.

otherwise i have a function getChatMessages which i import from custom hook deep inside App.js which sets the messages. this func is not a child of App.js and it is not wrapped with observer chatMsgStore.setChatMsg(firstResData) works! i can set the message so the observer component will re-render
how to make this code in useeffect above work?

Rob
  • 14,746
  • 28
  • 47
  • 65
user2177459
  • 97
  • 3
  • 9
  • observer is not needed here. reaction is not needed here. because i dont render anything in App.js component, i just using addChatMsg(bdmsg) method which adds data into the store. i dont know what was the problem but now the code above works great. – user2177459 Jan 19 '22 at 16:58

2 Answers2

0

you should use autorun from mobx in order to set correctly the reactivity in useEffect, here is a link to the doc that explains why and how use it.

But I think that you should not put chatMsgStore.chatmsg inside the deps array because you're not using it inside the useEffect.

If you can provide a working example maybe we can help you further.

Marco Nisi
  • 1,211
  • 10
  • 13
0

Your App component is not wrapped with observer HOC so it won't react to observable values changes.

Wrap it like that:

const App = observer(() => {
  // ...
})

or when exporting:

export default observer(App)

More info in the docs

Danila
  • 15,606
  • 2
  • 35
  • 67