Categories
React Answers React Native

How to create a weather app with React Native?

(Source code is at https://github.com/jauyeunggithub/rook-hotel-answers/blob/master/q5.txt)

Sometimes, we want to create a weather app with React Native.

In this article, we’ll look at how to create a weather app with React Native.

How to create a weather app with React Native?

To create a weather app with React Native, we can make requests to a weather API to get weather data when someone enters a query in the search box.

For instance, we write:

import * as React from 'react';
import { Text, View, StyleSheet } from 'react-native';
import Constants from 'expo-constants';

// You can import from local files
import { useState, useEffect } from 'react';
import { Card } from 'react-native-paper';
import { TextInput, Button } from "react-native";


export default function App() {
  const [data, setData] = useState({});
  const [query, setQuery] = useState('');

  const getWeather = async () => {
    const res = await fetch(`https://www.metaweather.com/api/location/search/?query=${query}`);
    const [{woeid}] = await res.json();
    const resWeather = await fetch(`https://www.metaweather.com/api/location/${woeid}`);
    const d = await resWeather.json();
    setData(d);
  };

  return (
    <View style={styles.container}>
      <TextInput value={query} onChange={e => setQuery(e.target.value)} placeholder='Type Location to Search' />
      <Button title='Search' onPress={getWeather} />      
      <Card>
        {JSON.stringify(data)}
      </Card>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    paddingTop: Constants.statusBarHeight,
    backgroundColor: '#ecf0f1',
    padding: 8,
  },
});

We define the data state to store the weather data.

And we have the query state to store the query input value.

Next, we define the getWeather function to make GET requests to the MetaWeather API with fetch.

And we call setData to set data to the result of the 2nd request.

Then we render a Virew with a TextInput to let users enter a query to search for weather data.

We have a Button which calls getWeather to make requests for the weather data according to the query value.

Then we display the retrieved data in a Card.

We add some styles to the View to center the content with justifyContent set to center and set a backgroundColor.

Conclusion

To create a weather app with React Native, we can make requests to a weather API to get weather data when someone enters a query in the search box.

Categories
JavaScript Answers Nodejs

How to read a CSV text file with Node.js?

(Source code is at https://github.com/jauyeunggithub/rook-hotel-answers/blob/master/q3.txt)

Sometimes, we want to read a CSV text file with Node.js.

In this article, we’ll look at how to read a CSV text file with Node.js.

How to read a CSV text file with Node.js?

To read a CSV text file with Node.js, we can use the fs.readFile method.

For instance, if we have:

foo.txt

id,name,value
1,James,50
2,Pete,300
3,Jane,400
4,Alex,200

Then we write:

const fs = require('fs')
fs.readFile('./foo.txt', (err, file) => {
  const rows = file.toString().trim().split('\n')
  let total = 0
  for (const r of rows) {
    const [, , val] = r.split(',')
    if (!isNaN(+val)) {
      total += +val
    }
  }
  console.log(total)
})

to import the fs module with require.

Then we call readFile with the file path and a callback to get the file content from the file parameter.

We call file.toString to convert the contents to a string.

Then we call trim and split to trim and split the string by the new line character.

Next, we define total and loop through rows to get the value of the number column and assign to val with destructuring.

Then we check if val is a number with isNaN and negation.

If it is, then we add it to total.

Therefore, we see total is 950 from the console log.

Conclusion

To read a CSV text file with Node.js, we can use the fs.readFile method.

Categories
JavaScript Answers

How to use modulo operator (%) in JavaScript?

(Source code is at https://github.com/jauyeunggithub/rook-hotel-answers/blob/master/q2.txt)

The modulo operator (%) in JavaScript lets us get the remainder when we divide one number by the other.

In this article, we’ll look at how to use modulo operator (%) in JavaScript.

How to use modulo operator (%) in JavaScript?

We can use the modulo operator to get the remainder of the left operand divided by the right one.

For instance, we write:

const numFn = (num) => {
  if (num % 14 === 0) {
    console.log('foobar')
    return
  } else if (num % 7 === 0) {
    console.log('foo')
    return
  } else if (num % 2 === 0) {
    console.log('bar')
    return
  }
  console.log('NUMBER')
}

We check if num can be divided by 14 evenly with num % 14 === 0.

If it is, we log 'foobar'.

Similarly, we do the same checks when dividing num by 7 and 2 and log different values.

Otherwise, we log 'NUMBER' if none of the conditions are true.

Conclusion

We can use the modulo operator to get the remainder of the left operand divided by the right one.

Categories
JavaScript Answers

How to get div tag scroll position using JavaScript?

Sometimes, we want to get div tag scroll position using JavaScript.

In this article, we’ll look at how to get div tag scroll position using JavaScript.

How to get div tag scroll position using JavaScript?

To get div tag scroll position using JavaScript, we can use the scrollTop property.

For instance, we write:

<div style='height: 100px; overflow-y: auto'>
  <p>hello</p>
  <p>hello</p>
  <p>hello</p>
  <p>hello</p>
  <p>hello</p>
  <p>hello</p>
  <p>hello</p>
  <p>hello</p>
</div>

to add a scrollable div.

Then we write:

const div = document.querySelector('div')
div.addEventListener('scroll', () => {
  console.log(div.scrollTop)
})

to select the div with document.querySelector.

Then we call div.addEventListener with 'scroll' to add a scroll event listener.

And in the listener, we log the value of div.scrollTop.

Now when we scroll the div up and down, we should see the scroll position of the div in pixels.

Conclusion

To get div tag scroll position using JavaScript, we can use the scrollTop property.

Categories
JavaScript Answers

How to pass variable through JavaScript from one html page to another page?

Sometimes, we want to pass variable through JavaScript from one html page to another page.

In this article, we’ll look at how to pass variable through JavaScript from one html page to another page.

How to pass variable through JavaScript from one html page to another page?

To pass variable through JavaScript from one html page to another page, we can use local storage to store the variable’s value.

Then we can get the value in the other page.

For instance, we write:

localStorage.setItem("name", 'jane');

to store an item with key 'name' and value 'jane' into local storage with localStorage.setItem.

Then on the other page, we can get the value with localStorage.getItem by writing:

localStorage.getItem("name");

which should return 'jane'.

Conclusion

To pass variable through JavaScript from one html page to another page, we can use local storage to store the variable’s value.

Then we can get the value in the other page.