I am currently working on creating a sample application using Mobx 6.9.0 and React Native/Expo. This is my current setup:
App.tsx
import { StatusBar } from 'expo-status-bar';
import { StyleSheet, Text, View } from 'react-native';
import { Provider } from "mobx-react";
import State from "./src/state";
import Sample from './src/sample/components/Sample';
export default function App() {
return (
<Provider store={State}>
<View style={styles.container}>
<Sample/>
<StatusBar style="auto" />
</View>
</Provider>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
Sample.tsx
import { View, Text, Button, TextInput } from 'react-native'
import React from 'react'
import { observer, inject } from "mobx-react";
function Sample(props: any){
const { count, updateCount} = props.store
console.log(count)
return (
<View style={{alignItems: 'center'}}>
<Text style={{fontSize:100}}>{count}</Text>
<Button
title='Press Me'
onPress={updateCount}
/>
</View>
)
}
export default inject('store')(observer(Sample))
state.ts
import { makeObservable, observable, action, computed } from "mobx";
class State {
constructor(){
console.log('New Store')
makeObservable(this, {
count: observable,
text: observable,
currentCount: computed,
updateCount: action
})
}
count = 0
text = ''
get currentCount(): number {
return this.count
}
updateCount(): void {
this.count += 1
console.log(this.count)
}
}
export default State
Whenever I press the button, I am expecting the updateCount to update and re render my Sample.tsx component. However, that is not happening; and the 'console.log(this.count)' is coming back as undefined.
I am expecting my count being displayed to update automatically, but I am not seeing what I am missing. Would someone be able to provide insight into this issue? Thanks!
Add below code on state file and Sample file
export default stateStore = new State();
and
function Sample(props: any) {
const { count } = props.store;
function increase() {
props.store.updateCount();
}
return (
<>
<View style={{ alignItems: 'center' }}>
<Text style={{ fontSize: 100 }}>{count}</Text>
<Button title="Press Me" onPress={increase} />
</View>
</>
);
}
sample link :https://snack.expo.dev/@rudiahmad/mobx-sample