Using an if statement following the iteration of a JSON object in a React Native application

I am currently working on a weather app using react native as a fun project. I have set up an API to fetch weather data in JSON format.

My goal is to show the hourly weather details based on the current time of the day.

export default class App extends React.Component {
constructor (props) {
  super(props);
  this.state = {
    isLoading: true,
  };
}
componentDidMount() {
const fetch = require('node-fetch');
 fetch('https://api.weatherapi.com/v1/forecast.json', {
   method: 'GET',
   headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json'
   },
 }).then((response) => response.json())
   .then((responseJson) => {
   console.log(responseJson);
     this.setState({
       isLoading: false, 
       dataSource: responseJson,  
     })
     console.log(responseJson.forecast.forecastday[0].hour[0].time.split(" ")[1]);
     const time = responseJson.location.localtime.split(" ")[1];
   }).catch((error) => {
     console.error(error);
   });
  
}
  render() {
    if (this.state.isLoading) {
  return (
    <View style={{flex: 1, paddingTop: 20}}>
     <ActivityIndicator /> 
  
  </View>
  );
    }
    return (
     <View style={{flex:1, paddingTop: 20}}>
      
       <Text style={styles.text}>{this.state.dataSource.location.name}</Text>

       <Text style={styles.mainText}>{this.state.dataSource.current.condition.text}</Text>

<Text style={styles.tempText}>{this.state.dataSource.current.temp_c + '℃'}</Text>

<View style={{flex:1, flexDirection: 'row', textAlign: 'center', paddingLeft: 90}}>

<Text style={styles.maxTempText}>{'H: ' + this.state.dataSource.forecast.forecastday[0].day.maxtemp_c + '℃'}</Text> 

<Text style={styles.maxTempText}>{'L: ' + this.state.dataSource.forecast.forecastday[0].day.mintemp_c + '℃'}</Text>
 </View>
 </View>
    );
    }
  }

   
  const myMainTime = () => {
    const mainTime = this.state.dataSource.forecast.forecastday[0].hour[0].time.split(" ")[1];
    {this.state.dataSource.forecast.forecastday[0].hour.map((item) => (
    if ( mainTime >= time ) {
    return ( 
      
      <ScrollView horizontal={true}>
      <View style={{flex:1, flexDirection: 'row', textAlign: 'center'}}>
          <View>
            <Text>{item.time.split(" ")[1]}</Text>
            <Image source={{url: "https:" + item.condition.icon}}
   
   style={{ width: 50, height: 50, paddingBottom: 10, alignItems: 'center',  justifyContent: 'center' }}
   />
   
   <Text>{item.temp_c + '℃'}</Text>
          </View>
   
        ))}
      </View>
      </ScrollView>
       )
  }
}

Below is the provided JSON data:

{
    "location": {
        "name": "New York",
        "region": "New York",
        "country": "United States of America",
        "lat": 40.71,
        "lon": -74.01,
        "tz_id": "America/New_York",
        "localtime_epoch": 1623928876,
        "localtime": "2021-06-17 7:21"
    },
    "current": {
        ...
                
(Please note that the rest of the JSON data has been omitted for brevity)
           

I want to iterate through the hourly weather data and only display the information within the app if the current time matches or exceeds the time in the JSON. Is there a way to achieve this?

Answer №1

When you examine the JSON data retrieved from the api, it includes a field called "time_epoch" for each hour (more information). Interestingly, this is also what you get when you execute Date.now in JavaScript, as explained here.

I'm not entirely certain about the other parts of your code, but by making this single adjustment, you can achieve the desired outcome:

...
  {this.state.dataSource.forecast.forecastday[0].hour.map((item) => (
    if ( Date.now() >= item.time_epoch ) {
      return ( 
...

Answer №2

If you want to exclude past data, you can use the current time to filter the array.

const now = moment().startOf('day').valueOf() // It's unclear if the date_epoch is in UTC or not; if it is, conversion to UTC time might be needed
const days = forecast.forecastday
               .filter(day => day.date_epoch * 1000 >= now)
               .map(futureDay => {
                 if(futureDay.date_epoch * 1000 === now) {
                   return {
                     ...futureDay,
                     hour: futureDay.hour.filter(hour => hour.time_epoch * 1000 >= Date.now())
                   }
                 }
                 return futureDay
               }

Answer №3

It is important to note that your current code will not work due to the absence of a function body.

If you wish to proceed, you can include a function body within the map method as shown below:

this.state.dataSource.forecast.forecastday[0].hour.map((item) =>
    Date.now() >= item.time_epoch ? (
      <ScrollView horizontal={true}>
        <View style={{ flex: 1, flexDirection: "row", textAlign: "center" }}>
          <View>
            <Text>{item.time.split(" ")[1]}</Text>
            <Image
              source={{ url: "https:" + item.condition.icon }}
              style={{
                width: 50,
                height: 50,
                paddingBottom: 10,
                alignItems: "center",
                justifyContent: "center",
              }}
            />

            <Text>{item.temp_c + "℃"}</Text>
          </View>
        ):null );
        </View>
      </ScrollView>
    ) : null
)

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

Tips for looping through client.get from the Twitter API with node.js and express

I am in the process of developing an application that can download a specific number of tweets. For this project, I am utilizing node.js and express() within my server.js file. To retrieve data from the Twitter API, I have set up a route app.get('/ap ...

Guide to mocking the 'git-simple' branchLocal function using jest.mock

Utilizing the simple-git package, I have implemented the following function: import simpleGit from 'simple-git'; /** * The function returns the ticket Id if present in the branch name * @returns ticket Id */ export const getTicketIdFromBranch ...

How to extract the HTML content from specific text nodes using Javascript

I have a piece of HTML that looks like this: <div id="editable_phrase"> <span data-id="42">My</span> <span data-id="43">very</span> <span data-id="1">first</span> <span data-id="21">phrase< ...

What is the reason for labels appearing inside select boxes?

Can someone help me understand why my select box label is displaying inside the select box? For example, when I am not using react-material-validator it looks like this: https://codesandbox.io/s/5vr4xp8854 When I try to validate my select box using the r ...

Ways to set a default value in AngularJS when there is no value to compare in an array

Hello, I'm a newcomer to AngularJS and I have the following code snippet in HTML: // Here, I have another ng-repeat loop where I compare home.home_info_id with avg.home_inof_id <div ng-repeat='home in homeDetailInfo'> <div ng-r ...

Is there a way to use nightwatch.js to scan an entire page for broken images?

Hi there, I'm currently working on creating a test to ensure that all images are loaded on a webpage with just one single test. I assumed this would be a straightforward task that many people have already done before, but unfortunately, I haven' ...

The UI bootstrap dropdown toggle requires two clicks to reopen after being manually closed

Utilizing the UI Bootstrap drop-down element to display the calendar from angular-bootstrap-datetimepicker upon clicking. Additionally, a $watch has been implemented to close the dropdown once a date is chosen. Access the Plunker here <div uib-dropdow ...

Searching for elements by tag name in JavaScript

Recently, I attempted to create JavaScript code that would highlight an element when a user hovers their cursor over it. My approach involves adding an event listener to every child within the first "nav" tag in the current document: let navigation = docum ...

Accessing deeply nested JSON objects in AngularJS

I've been working on an AngularJS single page application and I have successfully fetched files from a JSON. var app = angular.module("MyApp", []); app.controller("TodoCtrl", function($scope, $http) { $http.get('todos.json'). success ...

The clearTimeout function in React stateless components does not appear to be functioning properly

I am facing an issue with a component that I developed. In this component, one value (inclVal) needs to be larger than another value (exclVal) if both are entered. To ensure that the function handling this comparison doesn't update immediately when pr ...

Set the value of HTML input type radio to a nested JSON string

Currently, I'm developing an Angular application and encountering an issue where I am unable to access the nested array value 'subOption.name' for the input type radio's value. I'm uncertain if the error lies within the metaData st ...

Clicking on text triggers image display

My journey in coding is just starting and I have a good understanding of the basics of HTML, CSS, Javascript, and jQuery. I am trying to make an image appear when I click on text but struggling with the implementation. I'm working on a restaurant web ...

"Implementing a highlight effect on a selected item within a list in React Native with the Native Base UI kit: A step-by-step

I'm struggling to change the background color of the sidebar content using TouchableOpacity underlay. Adding TouchableOpacity only changes the text color, not the entire list background. I am working with the native base UI kit and need assistance in ...

What is the best way to receive a single response for various API endpoints?

I need to retrieve a single response from an API that has multiple page URLs. How can I accomplish this with just one API call? Here is my code: async function fetchArray () { // Fetch `urlArray` from object parameter let urlArray = []; ...

Issue detected: Props that are of type Object/Array must utilize a factory function in order to provide the default value

I recently started using Vue-Cli3.0 and came across this interesting module for Vue.js called https://github.com/holiber/sl-vue-tree It's a customizable draggable tree component for Vue.js, but I encountered an issue where it couldn't copy funct ...

When working with node.js, be cautious of using JSONP as it may lead to unexpected token errors if you

When working on my node.js function, I encountered an issue while using JSONP: this.send(JSON.stringify({ type: 'hello', username: this.data('username'), friends: friends })); The error reported was "unexpected token :", e ...

The function cannot be applied to the size of the map within the action payload

Is there a way to replace the for loop with the map method? The data structure for book.pages is in the format [{},{},{}] I tried using the size method and included this line console.log("book.pages.map.size();--->", book.pages.map.si ...

``Is there a way to effectively assess the Angular UI-Grid cellTemplate function in the attribute value only when it is displayed

Utilizing angularjs and ui-grid with a custom cellTemplate, each cell contains an object referred to as COL_FIELD. This object is passed to a function that generates an image data URI used in the src attribute of the cellTemplate to display images within e ...

What is the best way to enhance a state's capabilities in Machina.js?

When using Machina.js (version 0.3.6), how can I instantiate a modified FSM constructor where both the child and parent FSMs define behaviors in the same states? Here is the code snippet: var _ = require('lodash'); var machina = require('m ...

Design a unique input component tailored specifically for react-day-picker

While working on a custom Material UI component for DayPickerInput, I encountered an issue where the onDayChange event triggers an error. handleToDateChange = (selectedDay, modifiers, dayPickerInput) => { const val = dayPickerInput.getInput().value ...