Search code examples
reactjsreact-nativemobxmobx-react

Unable to get an updated value from mobx store


I am just trying out mobx, I have a simple component and a store. Whenever the button is pushed, I expect its text to be updated with a new timestamp. However, this doesn't happen and I don't know why. Here is the code:

import React from 'react';
import { Text, View, StyleSheet } from 'react-native';
import Constants from 'expo-constants';
import { Card, Button } from 'react-native-paper';
import { observer } from "mobx-react";
import { makeAutoObservable } from "mobx"

class State {
  timestamp = Date.now();

  constructor() {
    makeAutoObservable(this)
  }

  setTimestamp() {
    this.timestamp = Date.now();
  }
}

const state = new State();

const App = observer(() => {
  const { timestamp, setTimestamp } = state;

  return (
    <View style={s.root}>
      <Button onPress={setTimestamp}>
        {timestamp}
      </Button>
    </View>
  );
});

const s = StyleSheet.create({
  root: {
    flex: 1,
    justifyContent: 'center',
    paddingTop: Constants.statusBarHeight,
    backgroundColor: '#ecf0f1',
    padding: 8
  }
});

export default App;

Also available here: https://snack.expo.io/@pavermakov/react-native-mobx

I use the following dependencies:

"mobx": "6.0.1",
"mobx-react": "7.0.0"

Am I missing something?


Solution

  • With this piece of code:

    <Button onPress={setTimestamp}>
    

    You are losing the this context of your State class instance. When the button is clicked this actually refers to the Button element, so there is no Button.timestamp to change. The easiest way to fix this is to bind the setTimestamp back to the state class like this:

     <Button onPress={setTimestamp.bind(state)}>