@arttstyle
web-макака

Mobx данные is undefined?

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

export function chatMsgStore() {
    let chatmessages = []
    function setChatmessages(msgsArr) {
        chatmessages = msgsArr
    }
    return {chatmessages, setChatmessages}
}

export const chatmsgstore = () => useLocalObservable(chatMsgStore)


прокидываю через контекст
import {chatmsgstore} from "./src/store/chatmessages";

const App = () => {
    const AppFunctions = {chatmsgstore}
    return (<>
            <AppContext.Provider value={AppFunctions}>
                ................................
            </AppContext.Provider>
        </>
    )
};


пытаюсь дернуть внутри другого компонента
export function ChatApp() {
    const {chatmsgstore} = useContext(AppContext)


    console.log(chatmsgstore.chatmessages) <------ undefined ???
    chatmsgstore.setChatmessages([123,123,123]) <------- undefined is not a function???

    return ...............
}
  • Вопрос задан
  • 300 просмотров
Решения вопроса 1
Alexandroppolus
@Alexandroppolus
кодир
export const chatmsgstore = () => useLocalObservable(chatMsgStore)

это заменить на
export const useChatMsgStore = () => useLocalObservable(chatMsgStore)


далее
import {useChatMsgStore} from "./src/store/chatmessages";

const App = () => {
    const chatmsgstore = useChatMsgStore();
    const AppFunctions = {chatmsgstore}
...


----
можно подстраховаться на случай перерендеров App и проследить, чтобы значение в контексте не менялось:
const App = () => {
    const chatmsgstore = useChatMsgStore();
    const AppFunctions = useMemo(() => ({chatmsgstore}), [chatmsgstore]);
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы