Updating Variables Using State in React Native

Recently delving into the world of React, I've been experimenting with state and props. My current goal is to fetch data and use it to populate card views in my application.
Here's a glimpse of what my code looks like at the moment:

class Two extends React.Component {
constructor(props) { 
    super(props);
    this.state = { 
      day: "Monday",
    };
  }

// Retrieving monthly schedule
    getSchedules = () => {
        fetch("http://xxxxxx/getschedules.php", {method: "GET"})
        .then((response) => response.json())
        .then((responseData) => {
            AlertIOS.alert(
                "GET Response",
                "Search Query -> " + responseData.result.length)
                this.setState({day: responseData.result[1].day}); //modifying state but no visible change
        })
        .then((data) => { 
         console.log(data);
        })
        .catch(function(err) {
         console.log(err);
        })
        .done();
    }

  render() {  
            <TouchableOpacity onPress={this.getSchedules}>;
              <View style={styles.card}>
              <Text>{this.state.day}</Text>
              </View>
              </TouchableOpacity>
             }
}

Upon clicking on the card, the text value should update yet remains stagnant. Is there a way for the state to automatically adjust upon page load without requiring interaction from the user? Any assistance would be greatly valued!

Answer №1

When writing your onPress code, make sure to include the bind method like this:

<TouchableOpacity onPress={this.fetchData.bind(this)}>

If you don't use the bind method, the context of this won't be passed to your fetchData function.

Answer №2

Did you ensure that the fetch operation is functioning correctly?

I tested your script using a Facebook example URL and encountered

Network Request Failed

error message in the console (CMD + D - Debug)

By following the instructions provided in this Stack Overflow response to include the domain in an exception list within info.plist, I was able to resolve the issue :)

The info.plist file can be found in Xcode and updated easily by right-clicking, then selecting "Open as > Source Code" - this allows for easy copy-pasting of code from the aforementioned SO response.

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

Validating Input Textbox Content with JQuery Validation Plugin

I am currently utilizing the JQuery Validation plugin found at http://jqueryvalidation.org/ and encountering a specific scenario: Here is an example of the HTML code I am dealing with: <input type="text" name="glass_name" id="glass_name"> &l ...

Is there a more straightforward method than using a recursive function to serialize a JavaScript object for an AJAX request?

Check out this function and helper I created for serializing a javascript object to send in an ajax request. While there may be more efficient solutions in libraries like jQuery, I couldn't find one specifically for a javascript object. /* @author Be ...

Assign local variable in Mongoose using query results

I created a function to query MongoDB for a credential (simplified): var query = Credential.findOne({token: token}); return query.exec(function (err, credential) { if (err) return null; return credential; }); The next step is to use this credent ...

The challenges of $location.search().name and base href in application URLs

I am working on an Angular app and my URL appears as http://localhost:8080/personal?name=xyz. To extract the 'xyz' value in JavaScript, I am using $location.search().name. Here is a snippet of my code: app.js app.config(function ($locationProv ...

The splash screen fails to show up when I launch my Next.js progressive web app on iOS devices

Whenever I try to launch my app, the splash screen doesn't show up properly. Instead, I only see a white screen. I attempted to fix this issue by modifying the Next Metadata object multiple times and rebuilding the PWA app with no success. appleWebApp ...

AngularJS: Service variable not triggering $watch when updated within a directive's call

When I modify the service variable using a controller function, the $watch is triggered. However, it does not trigger when the same variable is changed by a directive. <html> <head> <meta charset="UTF-8"> <script src = "https:/ ...

Issue with php and ajax causing loop malfunction

I'm currently working on building a simple USD to pounds converter using PHP and AJAX. While I know it would be simpler with jQuery, unfortunately, the use of jQuery is not allowed for this assignment. The problem I'm facing is that when I run th ...

Encountering issues with installing @vue/cli on Linux Ubuntu

Currently facing an issue while attempting to install the Vue CLI on Ubuntu (WSL). After running both yarn add global @vue/cli and npm install @vue/cli --global, it seems like the commands were successful. However, upon checking the version using vue --v ...

Issue with Angular filter not being effective within ng-repeat

For all code regarding this issue, please visit: Filter: <input type="text" ng-model="search"> <tr ng-repeat="(id, group) in groups | filter:search" class="editing-{{group.editing}}"> The goal is to have the rows filtered out based on the in ...

Prevent Buttons from Being Clicked While Another is Active in Angular

I am facing a challenge with my Angular functions that enable search features. My goal is to allow only one feature to be selected at a time. /* Trauma Search functionality */ $scope.traumaSearch = false; $scope.traumaText = "Trauma Center"; $scope.togg ...

Are there any options for a JavaScript coding platform that can be used on a tablet device?

As someone who frequently travels by train, I recently purchased an Android tablet and have a strong desire to learn JavaScript. While I can read books on my tablet, I am eager to also be able to program on it. Are there any options available for develop ...

How to toggle classes in AngularJS using ng-class across various elements

I found a solution on this S.O. question to toggle a class using ng-click in AngularJS. Specifically, I am trying to show a Font Awesome closed folder icon when a list element is not clicked and an open folder icon when the list element is clicked within a ...

Can you explain which variable is considered global in Node.js?

Instead of writing var global = window for the browser I want my code to be able to work in a node environment as well. Something like var global = window || node_global What is node_global? I couldn't find any clear answer here: or here https ...

JQuery is having issues with $(this) and the find function not working properly

I am attempting to access a child of the div with the class form-group, specifically, I want to display the value of the input element. <div class="form-group"> <label>text</label> <input name="text" type="text" class="form-co ...

Using the prevState argument causes the useState to trigger multiple times during updates

Is there a way to capture the Event value and only add it once to a new Array without useState firing multiple times? const [receivedItems, setReceivedItems] = useState([]); const [newItems, setNewItems] = useState([]); //Capture selected value const hand ...

Using npm to install packages with multiple package.json files

My current project includes a submodule with another submodule, each having their own package.json file. This is how I set up my project: |root ----|node_modules ----|package.json ----|someFolder ----|submodule_1 -------- |package.json -------- |someFold ...

Are there alternative methods for adding attributes to a component in React?

function Greeting(props) { return <h1>Greetings, {props.person}</h1>; } function Display() { return ( <div> <Greeting person="Sara" /> <Greeting person="Cahal" /> <Greeting per ...

What is the best way to manage photos from your phone without having to upload them online?

I'm currently developing an application using AngularJS/Javascript, HTML, and CSS within a cloud-based environment on c9.io. My next task is to create and test an app that can access the phone's photo album, apply filters to images, and I'm ...

Error message indicating an attempt to access a property of an undefined object

When attempting to utilize an array to achieve a specific outcome, I encounter the cannot read property of undefined error. Oddly enough, when I console log the same property, I get the desired result. Below is my code: for (var j=0;j<$scope.ftListe.le ...

"Concealing specific routes in Vue Router depending on a certain condition - what's the

I need to determine which routes to hide based on a condition that evaluates to true or false. I have a collection of routes, such as: - Products - Clients For instance, if a user logs in but does not have the permission to edit products, then the updated ...