Issue with updating state in MobX/React Native when an action is triggered

I am currently in the process of developing a sample application using Mobx 6.9.0 with React Native/Expo. Here 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

When I click the button, I anticipate the updateCount to modify and re-render my Sample.tsx component. However, that's not occurring; instead, 'console.log(this.count)' returns undefined.

I'm hoping for an automatic update to display my count, but I seem to be overlooking something. Can someone offer insight into this issue? Thanks!

Answer №1

Insert the following code into your state and sample files:

export default stateStore = new State();

Additionally, include the following function in your Sample component:

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>
    </>
  );
}

For a live example, check out this link:

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Dependencies exclusively for NPM post-installUnique Rewrite: "N

I have been using git to distribute an internal TypeScript NPM package. To avoid cluttering my repository with build files, I have implemented a postinstall action to build the package upon installation: "postinstall": "tsc -p tsconfig.json& ...

Issues arise in TypeScript 5.1.3 with lodash due to type errors involving excessively deep type instantiation, which may potentially be infinite

Recently, I made updates to my Ionic/Angular project and now it is running Angular version 16.1.3 along with TypeScript version 5.1.3. In addition to this, my project also includes the following dependencies: "lodash-es": "^4.17.21", ...

Exploring the implementation of initiating paypal in NestJs using Jest testing framework

Currently, I am creating a test for a method within NestJs that is responsible for initiating a Paypal Payment intent. When I execute either the yarn test:watch or simply yarn test command, the test described below runs successfully and passes. However, up ...

The parameter in Angular cannot be assigned a type of 'null'

@Injectable({ providedIn: 'root' }) export class AuthenticationService { private currentUserSubject: BehaviorSubject<User>; public currentUser: Observable<User>; constructor(private http: HttpClient) { this.curren ...

The Expo MediaLibrary.getAssetsAsync({album:album}) function is not displaying the specified album in React Native

I am currently using Expo MediaLibrary to retrieve videos from a specific folder, and I have encountered an issue. When utilizing MediaLibrary.getAssetsAsync(), it appears that there are no media files inside the designated album, despite there being medi ...

What could be causing TypeScript to raise an issue when a /// reference comes after the 'use strict' statement?

This particular inquiry is somewhat connected to a question I posted on Stack Overflow yesterday about why TypeScript is encountering issues when trying to import a module. The initial configuration remains unchanged. My TypeScript file appears as follows ...

What is the proper way to add additional properties to an array object when initializing it in TypeScript?

Is there a more elegant solution for creating an object of type: type ArrayWithA = [number, number, number] & { a: string }; I accomplished this by: const obj : any = [1, 2, 3]; obj.a = "foo"; const arrayWithA : ArrayWithA = obj as ArrayWith ...

Using TypeScript with async await operators, promises, and the memoization pattern

I am currently in the process of updating my code to incorporate the latest TypeScript enhancements. We have implemented various memoization patterns, with the main goal being to ensure that services with multiple subscribers wait for one call and do not t ...

Discovering all words that conclude with a colon (:) utilizing regex

Looking for some guidance with regex, I am new to it. Specifically, I want to use a regular expression to find words or consecutive words that end with a colon(:). Incarcerate: imprison or confine, Strike down: if someone is struck down, especially by an i ...

Is it feasible to programmatically define the onClick action for an element within a ReactNode?

Let's discuss a function called addAlert that adds messages to an array for display as React Bootstrap alerts. While most alerts are simple text, there's one that comes with an "undo the last action" link. The challenge is that when this "undo" l ...

What steps can I take to persistently subscribe to SignalR from an Angular service even in the event of connection failures?

Is there a way to safely attempt to connect to SignalR with intervals between attempts until the connection is established? Also, does anyone have advice on how to handle the different stages of connectivity to the web sockets effectively? We are utilizin ...

Managing asynchronous data retrieval using rxjs

Within my service, I use an Observable to load data in the constructor. Later on, this data can be accessed using a getter, which should either return the data immediately if it's available or wait until the loading process is complete. Here is an exa ...

Storing a byte array in a local file using JavaScript: A Step-by-Step Guide

Recently, I encountered an issue while working with an openssl certificate. Specifically, when I tried to download the certificate from my API, it returned byte arrays that I needed to convert to a PEM file in order to access them through another API. The ...

options argument containing a keyof this

When defining a method type signature, it is possible to use keyof this to restrict an argument to the string name of a valid key of the class. However, using this approach does not work when the method accepts options-style arguments instead of positional ...

Having trouble implementing the 'cursor: pointer' hover effect using JSS in a React Typescript project

I'm attempting to incorporate a simple hover effect (browser standard cursor pointer behavior) into an existing React-Typescript project. After exploring various methods to achieve this, as React doesn't natively support CSS hover styles with in ...

Even though there is data stored in the array, the React Native array.length appears to be returning a value

I am struggling with what appears to be a simple issue, and it's frustrating that I've had to seek help for this. The problem lies in iterating through an array messages: Message[] = [...]. No matter what method of iteration I try, it doesn&apos ...

Ways to enforce TypeScript return type and prevent implicit casting

I am facing an issue with a method in my code that fetches data from an external API and returns it. The problem lies in the fact that the data type being returned is incorrect. The function's return type is IClickupTeam, but the actual data returned ...

Using Typescript in NextJS 13 application router, implement asynchronous fetching with async/await

Recently, I implemented a fetch feature using TypeScript for my NextJS 13 project. As I am still getting familiar with TypeScript, I wanted to double-check if my approach is correct and if there are any potential oversights. Here is the code snippet from ...

Is it possible to send prop as an object property in a TypeScript-based React component?

I am struggling with a persistent issue: export const LIST_OF_TYPES = { TYPE1: 'type1', TYPE2: 'type2', }; In the element, I specify the classification as such: export type IComponentCategoryType = 'type1' | 'type2&a ...

Develop a specialized data structure for rows in ag grid that can adapt to changes

I have been working on creating an independent component using ag-grid. The column definitions are passed to this component from my application as input properties, defined like this: interface ColumnDef { field: string; headerName: string; } @Input() ...