Reference being passed outside of function

I have been implementing a server using the package available at https://github.com/futurepress/react-native-static-server. The server has two main functions, namely server.start() to initiate the server and server.stop() to terminate the server. The method responsible for starting the server is _startServer(). However, I am facing an issue on how to correctly pass the reference to the server to stop it using the _stopServer() function.

export default class Foo extends Component {

    _startServer = () => {
        server.start()
            .then((localServer) => {
                this.setState({
                    serverRunning: true,
                    localServer: localServer
                })
            });
     }

     _stopServer = (refToServer) => {
          refToServer.stop();
     }

     ...

     render() {
         return (
            <TouchableOpacity
                onPress={() => this._startServer()} />

            <TouchableOpacity
                onPress={() => this._stopServer(??)} />
         )
     }
}

Answer №1

Incorporate the localServer into the Component's state by utilizing the following method:

this.setState({
               serverRunning: true,
               localServer: localServer
           })

By doing so, you can access the server using this.state.localServer and halt it using this.state.localServer.stop()

An example implementation would look like this:

_haltServer = () => {
          this.state.localServer.stop();
     }

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

Leveraging async to execute numerous functions

Suppose you have the following code snippet: public async void Init(){ init1(); init2(); init3(); } The first question is, are the methods running asynchronously or not? It's important to note that the methods themselves are declare ...

What are the steps to fix the eslint error related to "Generic Object Injection Sink"?

I'm attempting to access a JSON array, but every time I try to read the array/value by passing the JSON object key like this- json[key] An Eslint error occurs- [eslint] Generic Object Injection Sink (security/detect-object-injection) I understand ...

Creating a user-friendly HTML form to convert multiple objects into JSON format

Edited content: $.fn.serializeObject = function() { var obj = {}; var arr = this.serializeArray(); $.each(arr, function() { var value = this.value || ''; if (/^\d+$/.test(value)) value = +value; if (obj[this.name] !== u ...

Create dynamic div animations triggered by changes in size of another div

Struggling to get this animation to function correctly. I have a vertical scrolling page with various sized div elements that change based on the content. The problem is that when these size changes occur, the other elements are moving abruptly. I want to ...

Receiving no communication from Express Router

Having trouble receiving a response from the server after making get/post requests. I've tried adjusting the order of functions in index.js without success. I also attempted to send a post request using Postman to localhost:8080/register, but the requ ...

JavaScript data-interval for mobile browsers like opera mini

I am currently experiencing an issue with implementing the setInterval function on my website. Below is a snippet of the code where I am attempting to increment a count by 1 and display it on the screen: <div id="test"></div> <script> ...

Utilize JavaScript to dynamically modify the position of an HTML element

I am working on a script that can manipulate the size of a period symbol, making it increase and decrease in size while staying in one place. However, I have encountered an issue where the element moves up or down the page when its size changes. I tried ...

In which part of my code should I implement the string to numerical function for my OrderBy function?

I successfully implemented a sortable header for my table with no errors, everything is functioning as expected. However, there is a small issue that I anticipated beforehand. The data in my JSON is string-based with numerical values that include symbols l ...

troubleshoot using Visual Studio Code

Here's the scenario: I need to debug a project using VS Code. The project is usually started by a batch file and then runs some JavaScript code. Now, I want to debug the JavaScript code, but I'm not sure how to do that. If anyone has any instruct ...

What is the best way to manage a batch of files in a response from an Ajax POST request?

Currently, I am utilizing the OGRE web client to convert GeoJSON text data into ESRI shapefiles by making a POST request with Ajax. var data = { "type": "FeatureCollection", "features": [{ "type": "Feature", "geometry": { "type": "Point", "coord ...

Retrieve an item from an array based on the unique ID value of the button that was clicked using

I am working with a phones array that is populated with JSON data: var phones = [ { "age": 0, "id": "motorola-xoom-with-wi-fi", "imageUrl": "img/phones/motorola-xoom-w ...

Add information to the database using JavaScript within the ASP.NET C# framework. Once the data has been successfully inserted into the database, I aim to display an alert

Is it possible to use JavaScript to insert data into a database in an ASP.NET C# environment? If so, after successfully inserting the data, how can an alert box be created? ...

Steps for Resolving Vue Warning: There Could Be an Infinite Update Loop in a Component's Render Function

I keep receiving an alert for a possible infinite loop in my code. I suspect it's because I'm modifying a variable within the template's for loop using a method call. Any suggestions on how to resolve this issue? Although the loop does finis ...

What is the best way to iterate through an array containing multiple objects in order to create a graph?

My API response contains multiple objects organized in an array: [{"symbol":"AAPL","date":"2020-02-27","adj_close":68.24}, {"symbol":"TSLA","date":"2020-02-27","adj_close":133.8}, {"symbol":"TSLA","date":"2020-02-28","adj_close":122.3}, {"symbol":"AAPL" ...

Issue encountered when validating password through submission rate limiting

On my login page, I perform validation on the Email and Password entered by the user using submission throttling from the database. However, I encountered an error stating 'undefined index: txtMail' on the validate page. To track the server-side ...

Executing JavaScript code only if certain date conditions are satisfied

I'm trying to come up with a way to execute a piece of JavaScript code when a specific date condition is met: For instance: Do not run the code if the date falls between June 6th, 2014 5PM CST and June 16th, 2014 5PM CST. Or maybe the opposite wou ...

Steps for eliminating the #id from a URL page

Can someone assist me in removing or hiding my #id from the URL browser? For example: My menu1 targets "#p1" My site is "mysite.com/index.htm" When I click menu1 on my browser, it will show as "mysite.com/index.htm#p1" I want my id to not show on the U ...

Ensuring Security: Incorporating Authentication Tokens in $resource Requests with AngularJS

I am looking to include an authentication token when making requests to my API for resources. I have set up a service using $resource: factory('Todo', ['$resource', function($resource) { return $resource('http://localhost:port/t ...

Executing TypeScript compiled code in NodeJS from an HTML file

Being a novice in the world of NodeJS, I am currently diving into the realm of TypeScript. While navigating through Microsoft's TypeScript-Node-Starter, I stumbled upon a query regarding the functionality of the application. Here's what I' ...

Reveal content as you scroll

I'm having trouble with the code snippet below. My goal is to utilize .cbp-fbscroller in my CSS to show a new side navigation menu on my HTML page only when scrolling down to 900px. However, as someone who is new to JavaScript, I am struggling to make ...