Establishing and attaching a state in React Native

Currently, I am working on a timer application in React Native and aiming to display the elapsed milliseconds using state management. The guide I am referring to is slightly outdated as it uses plain JavaScript instead of ES6, so I took it upon myself to convert the code into ES6 syntax. However, I encountered a small issue where pressing the start button triggers an error mentioning that 'undefined' is not a function. Despite my attempts to rectify this by adjusting several elements, nothing seems to work.

...

class App extends Component {
   constructor(props) {
      super(props);
      // Initialize your state here
      this.state = {
         timeElapsed: null
      }
   }

   // getInitialState() {
   //    return {
   //       timeElapsed: null
   //    }
   // }

   render() {
      return (
         <View style={styles.container}>
            <View style={[styles.header, this.border('yellow')]}>
               <View style={[styles.timerWrapper, this.border('red')]}>
                  <Text>
                     {this.state.timeElapsed}
                  </Text>
               </View>

               ...
         </View>
      );
   }

   ...

   handleStartPress() {
      let startTime = new Date();

      // Update our state with some new value
      setInterval(() => {
         this.setState({
            timeElapsed: new Date() - startTime
         });
      }, 30);
   }

   ...

}

I am seeking advice on resolving this matter using JavaScript and ES6. My intuition suggests that the issue may be related to the binding process, but my efforts have not yielded any positive outcomes yet. Any assistance offered would be greatly appreciated! Thank you in advance.

Answer №1

Here is a suggestion for your code:

import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  TouchableOpacity
} from 'react-native';

export default class HelloReact extends Component {

  state:{
    timeElapsed : String;
  };

  constructor(props: Object) {
    super(props);
    this.state={timeElapsed : 'start'}
  };

  handleStartPress = () =>{
    let startTime = new Date();
    setInterval(() => {
        this.setState({
            timeElapsed: new Date() - startTime
        });
    }, 30);
  }

 render() {
  return (
      <TouchableOpacity onPress={this.handleStartPress} style={styles.container}>
         <View style={styles.container}>
                <Text>
                     {this.state.timeElapsed}
                </Text>
        </View>
     </TouchableOpacity>
  );
 }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
});

AppRegistry.registerComponent('HelloReact', () => HelloReact);

If you use Arrow Functions like this: handleStartPress = () => { ... } , you won't need to bind your function using this: this.handleStartPress.bind(this).

Answer №2

My issue was resolved by binding the handleStartButton function, which is called from another function named startStopButton

startStopButton() {
   return (
      <TouchableOpacity onPress={this.handleStartPress.bind(this)}>
         <Text>Start</Text>
      </TouchableOpacity>
   )
}

I left the handleStartButton function unchanged

handleStartPress() {
   let startTime = new Date();

   // Update our state with some new value
   setInterval(() => {
      this.setState({
         timeElapsed: new Date() - startTime
      });
   }, 30);
}

It's important to remember when using ES6 that you need to bind those functions for the correct outcome) Peace)

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

Creating a reusable field for reactive forms in Angular: A step-by-step guide

I need assistance with creating a versatile field component for reactive forms, but I am facing challenges in retrieving the value from the custom-input element. <form [formGroup]="form" (ngSubmit)="submit()"> <custom-input i ...

The failure to upload the APK was due to an error indicating that the keystore had been altered, even though no changes had actually been

I recently encountered an issue when trying to update my app on the Play Store. The error message indicated that the keystore had been changed, even though I had not made any changes to it. To resolve this issue, I created a new release apk and successfull ...

create a sapper route using JSON data

Beginning with the official Sapper template, I am keen on implementing export default as recommended by eslint: export default function get(_, res) { res.writeHead(200, { 'Content-Type': 'application/json', }); res.end(conte ...

Submit a data array using formData through axios

I am planning to send array data using formData. The backend is set up to accept the data array separated by a dash ; For example, if I were to use Postman and input the form-data like this: id_barang : 122;288;383 (sending 3 values of id with dashes ;) W ...

Instructions on sending search fields by pressing the enter key

Developing my application in React.tsx, I have a menu window that consists of numerous div elements with input fields, checkboxes, and select elements. Upon clicking the submit button, a list of results with user-selected filters appears. As an additional ...

What is the best way to position scale descriptions correctly?

The alignment of the Low and High scale descriptions over the first and 7th option in the image below is not as precise as I had hoped. While attempting to create elements with styles that match the scale closely in Bootstrap, I encountered difficulties in ...

Tips for modifying HTML attributes in AngularJS

I am looking to modify an attribute of a div using AngularJS. While I am familiar with how to do this in jQuery, I am not sure how to achieve it in Angular. Here is the HTML code: <div ng-app="test"> <div ng-controller="cont"> < ...

Unable to transfer the variable name between different node modules for the purpose of using it as a chat room identifier in a socket.io application

Users are able to provide a room name, however when using module.exports in a separate file to retrieve it, the value shows as undefined. This issue likely arises from the asynchronous nature of the process. //roomcheck.js var nsp = io.of("/gameroom"); n ...

Troubleshooting: Vue component does not refresh data when a function is

In my application, I have created two Vue components: Vue.component('event', { props:['event'], template: ` <span class="pointer" @click="showModal = true"> {{event.evname}} <modal @hide ...

When the focus() method is used to programmatically set the cursor in a JQuery input element, the blinking cursor does

I have a situation where I have two sibling divs. On the left side, I am loading a PDF document, while on the right side, I have input fields controlled by jQuery. My challenge arises when I try to select and delete the value from the input using the mous ...

Retrieving selected values from a dynamic Primeng checkbox component

Within my Angular app, I am managing an array of questions. Each question includes a text field and an array of string options to choose from. The questions are retrieved dynamically from a service and can be updated over time. To allow users to select mul ...

Reloading data in Angular using jQuery DataTables

After successfully implementing the jQuery datatables library, I encountered an issue where new data retrieved from my API was not displaying inside the datatable as expected. Instead, it was being shown below the table using ng-repeat. It seems that the d ...

Display a photo transitioning from black and white to color in a loading fashion, moving from left to right

Is there a way to enhance the clarity of the question's title? I have an interesting effect where text starts off in grey color and then transitions to black using keyframes in CSS with the animate property. I'm curious about how I can achieve ...

Click on the marker to view information about the location stored in the HashMap

A function is being used to store the json data in a hashmap. private Map<MarkerOptions, JSONObject> markersMap = new HashMap<MarkerOptions, JSONObject>(); private void parseLocationResult(final JSONObject result) { String id, place_ ...

Illustrative demonstration of AngularJS

One way to showcase data using AngularJS is by triggering a function with a button click. Here's an example: <!DOCTYPE html> <html ng-app> <head> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"& ...

Multiple executions can be triggered by ng-checked function

Here is the code snippet from the view : <input type="radio" name="tabset" id="tab2" aria-controls="rauchbier" ng-checked="switch_tabs()"> And in the controller, we have: $scope.switch_tabs = function(){ console.log(notificatio ...

Understanding when the @Input parameter has been modified

I need a way to trigger a function every time the @Input value is accessed, regardless of whether it has changed or not. Here's what I have tried so far: ngOnChanges(changes: { [propName: string]: SimpleChange }) { if( changes['inputName' ...

Set a dynamic Active Class on various divisions by utilizing their respective indexes

I have two divs with the same class. When I click on an anchor tag within one of the elements, I want to add a class to the corresponding position in the second div as well. Mirror: JSFiddle Here is the jQuery code snippet: $(document).on('click ...

Extracting JSON Value from a Script Tag

Seeking a more efficient method to extract the designated JSON value (highlighted in yellow) that is currently acquired using the code below. Although effective, it lacks efficiency. $("head > script:nth-child(55)").text().trim().replace(" ...

Tips for animating AngularStrap Collapse

My AngularStrap navbar collapse is functioning well, but the collapsing process lacks animation. Despite injecting the ngAnimate library and including the data-animation='am-collapse' attribute in my bs-collapse directive, I seem to have missed s ...