mobxjs / mobx-react

React bindings for MobX
https://mobx.js.org/react-integration.html
MIT License
4.85k stars 349 forks source link

Why do I have to use forceUpdate to update the view? #789

Closed chentianxin closed 5 years ago

chentianxin commented 5 years ago
const useThemeStore = () => {
  const isDarkMode = useMediaQuery('(prefers-color-scheme: dark)');
  const forceUpdate = useForceUpdate();
  const store = useLocalStore(() => ({
    theme: {
      type: isDarkMode ? 'dark' : 'light',
    },
    setType(val) {
      this.theme.type = val;
      forceUpdate();
    },
  }));

  return store;
};

const ThemeStore = ({children}) => {
  const {themeStore: {theme: {type}, setType}} = useRootStore(['themeStore']);
  const theme = createMuiTheme({
    palette: {
      type,
    }
  });

  return useObserver(() => (
    <ThemeProvider
      theme = {theme}
    >
      <button
        onClick = {() => {
          if(theme.palette.type === 'dark') {
            setType('light');
          }else {
            setType('dark');
          }
        }}
      >
        toggle
      </button>
      <CssBaseLine>
        {children}
      </CssBaseLine>
    </ThemeProvider>
  ));
};
danielkcz commented 5 years ago

You are missing an observer around the component. The useObserver is not enough because it cannot see changes to observables. Another way is to avoid destructuring and accessing through store within useObserver boundary should work.

chentianxin commented 5 years ago

import {useLocalStore} from 'mobx-react-lite';

const useChatStore = () => { const store = useLocalStore(() => ({ chatList: [], add(val) { this.chatList.push(val); }, }));

return store; };

export default useChatStore;

hatStore} = useRootStore(['chatStore']); const list = chatStore.chatList; const add = chatStore.add; useEffect(() => { let timer = setInterval(() => { add(timer); }, 1000); }, []); console.log(JSON.stringify(chatStore));

return useObserver(() => ( <>...</> )

After the state changes here, the view will be re-rendered.

danielkcz commented 5 years ago

Sorry, but prepare a CodeSandbox example if you need further help. Also, learn how to format text as a code in GitHub, this is horrible to read.

lock[bot] commented 4 years ago

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs or questions.