JavaScript Fundamentals & Fetch API
42 Questions
0 Views

Choose a study mode

Play Quiz
Study Flashcards
Spaced Repetition
Chat to Lesson

Podcast

Play an AI-generated podcast conversation about this lesson

Questions and Answers

What keyword is used to load values from other JavaScript files?

  • `let`
  • `import` (correct)
  • `const`
  • `var`

Which keyword is used to create a variable whose value cannot be reassigned after its initial assignment?

  • `var`
  • `const` (correct)
  • `let`
  • `import`

In React Native, what are the properties passed to a component's constructor called?

  • Props (correct)
  • State
  • Functions
  • Elements

Which of the following is a description of 'state' in React Native?

<p>An object with details about how a component should render (A)</p> Signup and view all the answers

What is the purpose of the export keyword in JavaScript?

<p>To expose values for importing into other files (B)</p> Signup and view all the answers

Which term describes the attributes of a React Native element?

<p>Props (D)</p> Signup and view all the answers

Which variable declaration should be avoided unless maintaining legacy code?

<p><code>var</code> (B)</p> Signup and view all the answers

What does the fetch() method primarily return?

<p>A promise that resolves with a Response object (A)</p> Signup and view all the answers

What is the purpose of the json() method when used with a Response object from the Fetch API?

<p>To parse the response body as JSON (D)</p> Signup and view all the answers

If you want to customize an HTTP request using fetch(), what is the purpose of the second argument?

<p>Customizes the HTTP request. (A)</p> Signup and view all the answers

What is a key advantage of the Fetch API over XMLHttpRequest?

<p>It is promise-based. (A)</p> Signup and view all the answers

What does the Fetch API provide for JavaScript?

<p>An interface for accessing and manipulating parts of the HTTP protocol (C)</p> Signup and view all the answers

Which HTTP concept does Fetch API integrate?

<p>CORS (C)</p> Signup and view all the answers

In a fetch request, to send data in the body, which method should be specified?

<p><code>POST</code> (A)</p> Signup and view all the answers

What method is used to convert a JavaScript object into a JSON string for sending in a fetch request body?

<p><code>JSON.stringify()</code> (D)</p> Signup and view all the answers

What is the simplest usage of the fetch() method?

<p>Taking one argument - the path to the resource. (C)</p> Signup and view all the answers

In React Navigation, how do you specify options that apply to all screens within a Stack Navigator?

<p>By passing <code>screenOptions</code> to the <code>Stack.Navigator</code> component. (B)</p> Signup and view all the answers

What does a JavaScript implementation in React Navigation allow?

<p>Greater customization (B)</p> Signup and view all the answers

What does navigation.navigate('RouteName') do in React Navigation?

<p>It pushes a new route to the stack only if it's not already present; otherwise, it jumps to that screen. (A)</p> Signup and view all the answers

How can you programmatically navigate back to the first screen in a stack using React Navigation?

<p>navigation.popToTop() (A)</p> Signup and view all the answers

Which of the following is a navigator type in React Navigation?

<p>Stack Navigator (A)</p> Signup and view all the answers

Which method is used to save data in AsyncStorage?

<p>AsyncStorage.setItem() (A)</p> Signup and view all the answers

What preprocessing tool does vanilla React Native use?

<p>Babel (C)</p> Signup and view all the answers

What function retrieves data from AsyncStorage?

<p>AsyncStorage.getItem(key) (D)</p> Signup and view all the answers

What does ES6 stand for?

<p>ECMAScript 6 (B)</p> Signup and view all the answers

Which AsyncStorage method removes a specific item?

<p>AsyncStorage.removeItem(key) (B)</p> Signup and view all the answers

What does AsyncStorage.clear() do?

<p>Clears all stored data (A)</p> Signup and view all the answers

Which method retrieves all keys in AsyncStorage?

<p>AsyncStorage.getAllKeys() (B)</p> Signup and view all the answers

Which function allows you to save multiple key-value pairs in AsyncStorage?

<p>AsyncStorage.multiSet(array) (D)</p> Signup and view all the answers

Which method is used to fetch multiple values from AsyncStorage?

<p>AsyncStorage.multiGet(array) (B)</p> Signup and view all the answers

Where should the NavigationContainer typically be placed in a React Native application?

<p>At the root of the app (C)</p> Signup and view all the answers

Which method selectively updates properties instead of replacing all child properties?

<p>update() (C)</p> Signup and view all the answers

What triggers the callback function in onValue()?

<p>For initial data and on subsequent data changes (B)</p> Signup and view all the answers

What does onValue return?

<p>An unsubscribe callback (A)</p> Signup and view all the answers

What will val() return if a location in the database has no data?

<p>Null (A)</p> Signup and view all the answers

What type of argument does the onValue method take?

<p>Query (D)</p> Signup and view all the answers

What is the data passed to the callback function in onValue()?

<p>A DataSnapshot (B)</p> Signup and view all the answers

What is the primary use of the onValue function?

<p>Reading data (A)</p> Signup and view all the answers

What is the effect of calling update()?

<p>It only updates the referenced properties. (A)</p> Signup and view all the answers

When does the onValue event trigger with the initial data?

<p>After the entire contents have been synchronized (B)</p> Signup and view all the answers

What kind of child property is 'name/first'?

<p>Relative Path (B)</p> Signup and view all the answers

Signup and view all the answers

Flashcards

Component

A modular, reusable building block of a user interface in React Native.

Import

Used to load values from other JavaScript files; uses relative paths.

Export

Used to make values available for importing by other JavaScript files.

Let and Const

Declares variables (can be reassigned) and constants (cannot be reassigned), respectively.

Signup and view all the flashcards

Props

Data passed from a parent component to a child component.

Signup and view all the flashcards

State

An object that determines how a component should render and respond to changes. Can't directly modify it.

Signup and view all the flashcards

JSX Attributes as Props

JSX attributes become props (parameters) of the React element.

Signup and view all the flashcards

navigation.navigate('RouteName')

Navigates to a route, pushing it onto the stack if not already present, otherwise jumps to it.

Signup and view all the flashcards

navigation.push('RouteName')

Pushes a new route onto the stack, even if it already exists.

Signup and view all the flashcards

navigation.goBack()

Programmatically goes back to the previous screen in the stack.

Signup and view all the flashcards

navigation.popToTop()

Goes back to the first screen in the stack.

Signup and view all the flashcards

Fat Arrow Functions

Cleaner, more concise way to define functions in ES6.

Signup and view all the flashcards

Fetch API

A modern JavaScript API for making network requests, offering a more powerful and flexible alternative to XMLHttpRequest.

Signup and view all the flashcards

fetch() Method

A global method in JavaScript that starts the process of fetching a resource from the network.

Signup and view all the flashcards

Basic Fetch Usage

Pass the URL of the resource you want to retrieve as an argument to the fetch() function.

Signup and view all the flashcards

Response Object

An object representing the entire HTTP response, including headers and body.

Signup and view all the flashcards

json() Method (Response)

A method of the Response object that parses the response body as JSON and returns a promise.

Signup and view all the flashcards

Customizing Fetch Requests

Customize your HTTP request by passing an optional second argument (an object) to fetch() to specify method, headers, body etc.

Signup and view all the flashcards

Method (Fetch Options)

Specifies the HTTP method for the request (e.g., 'GET', 'POST', 'PUT', 'DELETE').

Signup and view all the flashcards

Headers (Fetch Options)

Allows you to set HTTP request headers, such as Content-Type and Accept.

Signup and view all the flashcards

Body (Fetch Options)

The body of the HTTP request, typically used for POST or PUT requests to send data to the server.

Signup and view all the flashcards

update() method

Selectively updates specified child properties at a location without replacing all existing properties.

Signup and view all the flashcards

onValue function

Listens for data changes at a specific location in the Database. Triggers the callback initially and on every subsequent change.

Signup and view all the flashcards

Unsubscribe function

A function returned by onValue that, when invoked, stops the listener from receiving further updates.

Signup and view all the flashcards

Single Screen App

An app architecture where all content is displayed on a single screen, with different sections or views being shown or hidden as the user interacts with the app.

Signup and view all the flashcards

Native Navigation (React Native)

Utilizes native iOS and Android navigation components for React Native apps.

Signup and view all the flashcards

React Native Navigation

Relies on Javascript components for navigation.

Signup and view all the flashcards

DataSnapshot

A snapshot of the data at a database location at a particular point in time

Signup and view all the flashcards

unsubscribe()

Stops receiving database updates. Prevents memory leaks.

Signup and view all the flashcards

Database Reference (ref)

A reference to a specific location in your Database.

Signup and view all the flashcards

onValue event

A Database event that triggers once with the initial data and again whenever the data changes.

Signup and view all the flashcards

React Navigation

A navigation solution for React Native, offering customization and integration with the RN ecosystem.

Signup and view all the flashcards

JavaScript Implementation (Benefits)

Offers extensive customization, better fits the React Native ecosystem and allows growth independent of native platform navigation solutions.

Signup and view all the flashcards

Stack, Tab, and Drawer Navigators

Key components in React Navigation for structuring app navigation.

Signup and view all the flashcards

AsyncStorage Functions

Methods to store, retrieve, and manage data locally in React Native apps.

Signup and view all the flashcards

AsyncStorage.setItem(key, val)

Stores a value under a specific key.

Signup and view all the flashcards

AsyncStorage.getItem(key)

Retrieves the value associated with a given key.

Signup and view all the flashcards

AsyncStorage.removeItem(key)

Removes the stored value associated with a specific key.

Signup and view all the flashcards

AsyncStorage.clear()

Clears all data stored in AsyncStorage. Use with caution!

Signup and view all the flashcards

NavigationContainer

Wraps your entire app to provide navigation functionality.

Signup and view all the flashcards

NavigationContainer Usage

Should only be used once at the root of your app, unless you have specific use cases for multiple containers.

Signup and view all the flashcards

Study Notes

Lecture 2: Introduction to Components and JavaScript

Overview for today

  • The lecture covers components, let and cosntant, state and props, creating a component and events

Imports and Exports

  • import keyword loads values from other Javascript files via relative path
  • export keyword exposes values for importing

let and const

  • Use let and const to declare variables and constants.
  • Avoid variable declarations with var unless maintaining legacy code.
  • Example: let myVariable = 42,const myConstant = 42

Component API: Handling App Changes and Defining Props and State

  • Key question addressed: how to make an app respond to changes like button clicks or network requests

Component API: Props

  • Properties passed to the constructor of a component are called props.
  • Parents can pass props down to children, but not the other way.
  • JSX attributes become parameters called props of the React element.
  • Value of an attribute can be any JavaScript expression when wrapped in curly braces.
  • Example: bar={baz} which would set the value of bar prop to baz.

Component API: State

  • State: An object with details about how a Component should render.
  • Name of the object is literally state

Component API: Children

  • Any children element should go between the opening View tag, e.g <View> and closing View tag, e.g </View>.

Components

  • React components are reusable building blocks to create the user interface.
  • Components are the type of the React element.
  • Build-in components are View and Text.
  • Custom Component can also be defined

Defining Components

  • Two ways to define a React component: Function components and Class components.
  • Function components take parameters (called props) as input, and return a React element e.g.
function MyComponent({ title }) {
    return (
        <View>
            <Button title={title} color="#1ACDA5" />
        </View>
    );
}
  • Class components are a class that extends React.Component and implements a render method
class Mycomponent extends React.Component{
    render(){
        return (<View/>)
    }
}

Defining Function Components

  • Function component is a function that returns a React element.
import React from 'react' 
import { Button, View } from 'react-native'
export default function MyComponent() { 
    return ( 
        <View> 
            <Button title="Press me!" color="#1ACDA5" /> 
        </View> 
    )
}

Defining Class Components

  • Can create components by subclassing React.Component and overriding the render() method
  • Props are accessible as this.props

Composing Components

  • Custom Components like MyComponentcan be used as built-in ones like View.
  • Use props to communicate between components.

Events

  • Some components trigger events/callbacks in response to user input.
  • To add an event handler, pass a function as a prop to a React element.

Networking

  • Many mobile apps need to load resources from a remote URL.
  • Make a POST request to a REST API or fetch static content from another server

Using Fetch

  • React Native provides Fetch API for any networking needs.
  • Fetch will seem familiar if you have used XMLHttpRequest or other networking APIs before.

Making Requests

  • To fetch content from an arbitrary URL, pass the URL
  • Example: fetch('https://mywebsite.com/mydata.json');

Using the Fetch API

  • Fetch API provides a JavaScript interface for accessing and manipulating parts such as requests and responses.
  • Fetch API provides a global fetch() method for fetching resources asynchronously across networks, and it provides an easy, logical way of doing so.
  • Fetch is promise-based alternative whereas XMLHttpRequest is callback based.
  • Fetch integrates advanced HTTP concepts like CORS and other extensions to HTTP are integrated.

Basic Fetch Request

  • The simplest use of fetch() takes one argument path to the resource you want to fetch.
  • fetch() does not directly return the JSON response body but instead returns a promise that resolves with a Response object.
async function logMovies() {
  const response = await fetch("http://example.com/movies.json");
  const movies = await response.json();
  console.log(movies);
}

The Response Object

  • Response object does not directly contain the actual JSON response body and instead is a representation of the entire HTTP response
  • json() method is used to extract the JSON body content from the Response object; it returns a second promise that resolves with the result of parsing the response body text as JSON.

Making an HTTP Request

  • Fetch takes an optional second argument to customize the HTTP request.
    • It may specify additional headers or make a POST request.
fetch('https://mywebsite.com/endpoint/', {
  method: 'POST',
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    firstParam: 'yourValue',
    secondParam: 'yourOtherValue',
  });
});

Handling the Response

  • Networking is asynchronous operation so Fetch method will return a Promise to make straightforward to work with.
const getMoviesFromApi = () => {
  return fetch('https://reactnative.dev/movies.json')
    .then(response => response.json())
    .then(json => {
      return json.movies;
    })
    .catch(error => {
      console.error(error);
    });
};
  • Also use the async / await syntax in a React Native app
  • Remember to catch any errors that may be thrown by fetch

Basic Fetch Request

  • Example of using Fetch for web requests
import React, {useEffect, useState} from 'react'; // for managing state
import {ActivityIndicator, FlatList, Text, View} from 'react-native'; // to display our objects for our data 
const App = () => { 
    const [isLoading, setLoading] = useState(true); // initially set to true 
    const [data, setData] = useState([]); // in this way is gonna be an empty array 
    const getMovies = async () => { 
        try { 
            const response = await fetch('https://reactnative.dev/movies.json'); 
            const json = await response.json(); //put the response in Jason format 
            setData(json.movies); // we gonna set our data with json.moviw(movie inside Jason file in the website)
        } catch (error) { // catch the error 
            console.error(error); 
        } finally {     
            setLoading(false); // if the loading is false we can display our flat list 
        } 
    }; 
    useEffect(() => { // to use use effect that hook that we import 
        getMovies(); 
    }, []);

Security

Topics for storing sensitive information, authentication, network security, and tools the you secure your app

Storing Sensitive Info

  • Never store sensitive API keys in your app code
    • Tools to use in place: react-native-dotenv and react-native-config
  • If there needs to be an API build an orchestration layer using: AWS Lambda or Google Cloud Functions

Storing Sensitive Info (Best Practices)

  • Choose the right type of stoage based on sensitively
  • Persistent vs Unpersisted

Async Storage

  • Community maintained module for React Native asynchronous, uencrypted, key value store
  • Not dshared between apps = sandbox environment
  • DO use: for persisting non-sensitive data

Secure Storage

  • There are pre-existing solutions for Android and iOS platforms because React Native doesn't come bundled with any way of storing sensitive data
    • Keychain Services
    • Secure Shared Preferences

Lecture3A(Lists and TextInputs)

  • This lecture will introduce text inputs, as well as covering HOOKS,Scrollview, Flatlists and sectionlist

useState

  • useState is the first hook learnt
  • It can be used to intialize the state at the tope of your function component
  • Example*:
import { useState } from "react";
function FavoriteColor() {
const [color, setColor] = useState("");
  • We destructute the returned values from useState()
  • The first value is used for current states
  • The second value is used for updating the state

useEffect

  • useEffect is the second hook and lets you synchronize
  • useEffect react hook lets your synchronize component from external states
  • Syntax : useEffect(setup,dependencies?)
  • Call useEffect at the top level of your component to delcare an effect -setup: The function wit your Effect's logic -optional dependencies: The list of all reactive values referenced inside of the setUp cord
  • There are a variety of useEffect examples such as; no dependency passed, an empty array, or props or state values

ScrollView

  • Native React Component Library
  • Has multi-child options
  • Can scroll vertically or horizintally
  • It scrolls vetically, and to mention horizontal scroll we state horizontal: true

ScrollView Attributes

  • showsHorizontalScrollIndicator: Show an indicator for horizontal scrolling
  • ScrollEnabled: If we don't want to scroll our content, to define it false
  • horizontal: In case if we want to have horizontal scrolling, set the attribulte as true, horizontal = true

Flatlist

  • Like a listview, is used to hold items in a list -Provides important features like scolling horinzontally and verically -Designed to handle large datasets that might not fit on the device screen
    • Renders only current displaying items on a screen

Syntax for basic Flatlist

import {Flatlist } from 'react-native';
<FlatList
data={
// data to be rendered in flatlist
}
Separator Component={
// A separator to separate data items
}
renderData= {({ singledata})
// Single data view
}
/>

-Can rendered using 2 props. The flatlist

  • Other optional ones include Separator,Header,

RefeshControl

  • Provides and indivdual refeshControl
  • Implment pull-to-refresh to add the functions use RefreshingControl -when you initiate a pull to refresh gesture refershControl triggers
    • executes new data from the sever to add to on screen

TextInput

  • Fundatmental component for inputted text
  • Provides conficguaribility for functions; autocorrection,capitalation.

Lecture - Firebase Database

  • This lecture will cover local data / over network data + the set up for firebase
  • Local vs Over Network Data Table
Local Data Over network data
Performance and size are usually not an issue Fetches have to be tailored to what is needed, since it is fetched over the internet
Delivery is guaranteed Delivery depends on the user's network
Typically accessed by 1 session of the app at a time Accessed by an unknown number of sessions of the app at a time
Doesn't worry about concurrency Concurrency is at the heart of it

Is Firebase?

  • Firebase is a backend-as-a-service

Firebase Realtime Database

-Syncing with real time for JSON data, a could hosted, NoSQL database

  • Stores , syncs with and cloud database that remians -The SDK's share one Realtime Database interace with the newest data on the JSON's every connected client -Follow set up instructions at https://console.firebase.google.com/u/0/

Initialize SDK Into Project

import { initializeApp } from 'firebase/app';
// TODO: Replace the following with your app's Firebase project configuration
const firebaseConfig = {
 apiKey: 'api-key',
 authDomain: 'project-id.firebaseapp.com',
 databaseURL: 'https://project-id.firebaseio.com',
 projectId: 'project-id',
 storageBucket: 'project-id.appspot.com',
 messagingSenderId: 'sender-id',
 appId: 'app-id'
};
const app = initializeApp(firebaseConfig);
  • Follow set up instructions at https://console.firebase.google.com/u/0/

Realtime Database Refernces

  • Reference your JSON data like this users /users: phone-number

API

  • Ref imports ref to correspond return database, it contains root of database
  • set Writes data to location and overwrites it
    • Ex: set(ref(Db, id)
  • remove Imports the process of removing from the database Ex: remove(Ref)

onValue

  • Primary way for reading database. Callback will trigger from initial changes.
  • Invoke the returned callback to stop receiving updates

Studying That Suits You

Use AI to generate personalized quizzes and flashcards to suit your learning preferences.

Quiz Team

Related Documents

Description

Test your knowledge of JavaScript fundamentals including variable declarations, React Native, and the Fetch API. Explore concepts like state in React Native, exporting modules, element attributes, and customizing HTTP requests. Understand the advantages of Fetch API and its integration with HTTP.

More Like This

Use Quizgecko on...
Browser
Browser