react Flashcards

1
Q

react: In jsx, to write a css class attribute, you must write

A

className=”cssClass”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

react: A component “mounting” means

A

it is rendering for the first time

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

react: The three mounting methods that get called in order when you call ReactDOM.render() are

A

componentWillMount: right before the component renders. You CAN call this.setState() in this. Being deprecated, so don’t use.
render: the render function runs and injects the JSX
componentDidMount: right after the render function runs. Usually used to make API call for initial data, can use constructor. Also used to

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

react: componentDidMount only gets called

A

AFTER the very first rendering of a component. Using set interval to run ReactDOM.render() again will not retrigger it.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

react: componentWillReceiveProps will only get called if

A

a component is being passed in props

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

react: componentWillReceiveProps automatically gets passed one argument which is

A

an object called ‘nextProps’ which is the value of the prop that will be passed in

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

react: componentWillReceiveProps is an opportunity to

A

do something based on the new props a component is going use before render

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

react: files with jsx written in them must be

A

compiled before sent to browser

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

react: If a JSX snippet takes up multiple lines, you must

A

wrap it in parentheses.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

react: JSX must be

A

wrapped in one outermost element.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

react: ReactDOM.render() takes the arguments

A

component and location to inject it
ie
ReactDOM.render(-h1>Hello world-/h1>, document.getElementById(‘app’));

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

react: To render a JSX expression into the template, type

A

ReactDOM.render(-h1>Hello world-/h1>, document.getElementById(‘app’));

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

react: if you call

ReactDOM.render(hello, document.getElementById(‘app’));

and then again

ReactDOM.render(hello, document.getElementById(‘app’));

it will

A

do nothing because react will only render the same component in the same location again if it has changed

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

react: In JSX, self closing tags like input and img must

A

have a closing slack ie img />

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

react: To evaluate code inside of JSX,

A

wrap it in {} ie -h1>{2 + 3}-/h1> and the return will be rendered

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

react: The JSX in your file can access

A

all the variables in the environment

const theBestString = ‘tralalalala i am da best’;

ReactDOM.render(-h1>{theBestString}-/h1>…

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

react: event listeners (like onclick) in JSX must

A

be written in camelCase

onClick={funcName}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

react: To manipulate the element that sent an event, use

A
function functionName(e) {
  const element = e.target
}

ie the -img> src will change.

function changeImage(e) {
  e.target.setAttribute('src', 'https://url.com');
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

react: in JSX, you cannot

A

write if statements in the {} braces

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

js: To write a ternary, type

A

x > 10 ? y : z

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

js: To write a conditional using &&, type

A

x > 10 && functionName()

note: It is the same as a ternary but with no else

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

React: JSX can be rendered even if it is a

A

list of JSX objects.

const liArray = [
  -li>item 1-/li>, 
  -li>item 2-/li>, 
  -/li>item 3-/li>
];

-ul>{liArray}-/ul>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

React: To use map to make a list of JSX objects, type

A
const myJSXArray = myArray.map((item, key) =>
  -li key={key}>{item}-/li>
);
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

React: The steps for rendering JSX are

A

A JSX element renders.
The entire virtual DOM updates.
The virtual DOM “diffs,” comparing its current self with its previous self.
Part of the real DOM updates.
The screen looks different than it used to.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

js: Class and Component names must be written in

A

UpperCamelCase

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

js: importing and exporting modules

A

https://www.youtube.com/watch?v=Jqn_wjkSZwo

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

js: To import a file from a filepath instead of from the environment,

A

you must add the ./ to “./FileName” so node looks in the filepath.

Note, if there is no file type extension, node assumes it is .js

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q

js: To export something from your file (aka named export), type

A
export before any top level variable, function, or class
ie

export const myVar = “string”

then to import from same directory, type
import { myVarName, myFunctionName } from ‘./FileName’;

note: Curly brackets needed for named exports because there can be multiple, but default exports don’t need curly brackets
note: even if there is only one named export, you still need the curly brackets

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
29
Q

React: When sending in props to a component, the values that are not strings must

A

be in {} curly braces

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
30
Q

React: When passing an event handler function into a component as a prop, name the prop

A

the same as the name of the function.

ie 
handleClick() {}

the prop:
onClick = {this.handleClick}

note: onClick is only a special event listener when on regular html elements. On components it behaves just like any prop.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
31
Q

React: The name convention for naming event handler functions is

A

handleClick, handleMouseOver etc.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
32
Q

react: If a component has more than one child between its JSX tags, then

A

this.props.children will return those children in an array. But if a component has only one child it will return the single child, not wrapped in an array.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
33
Q

react: To give a component default props that will get called if this.props.propName was called but never passed in, type

A
class MyComponent extends React.Component {
  render() {
    return -h1>{this.props.text}-/h1>;
  }
}

MyComponent.defaultProps = { text: ‘string’ };

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
34
Q

react: To create a constructor and set initial state, type

A

constructor(props) {
super(props);
this.state = { mood: ‘decent’ };
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
35
Q

ES6: In between functions of a class

A

do not put a comma

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
36
Q

react: whenever you define an event handler that uses this, you must

A

add this.methodName = this.methodName.bind(this) to your constructor function.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
37
Q

react: this.setState automatically

A

calls render

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
38
Q

react: Stateless child components should only

A

update a parent component using a function the parent passed down to it through props

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
39
Q

react: To choose which component to add ReactDOM.render() to, you need to choose

A

the highest level one, which calls all the other components in its render function

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
40
Q

react: A component should use state to store

A

information that the component itself can change.

it should never change its props. If a child needs to change it’s props, it needs to get a handler function from the parent as a prop to call, not change it on its own.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
41
Q

react: Every event handler automatically passes in

A

an event argument into the function

onClick = {this.props.onClick}

in the parent function you can write

handleClick(e) {
  let value = e.target.value
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
42
Q

react: When an event is happening in a child component, that will then change a parent components state, often

A

you will create a function in the child component to process the event into a properly formatted value (e.target.value), and then call this.props.parentsFunction(formattedValue) from there, for clarity

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
43
Q

react: if you are repeating {this.props.propName} in the render function a lot, might as well

A
create a variable
let propName = this.props.propName
in the render function and just use {propName}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
44
Q

react: a common pattern is

A

A stateful component class defines a function that calls this.setState. (Parent.js, lines 15-19)

The stateful component passes that function down to a stateless component. (Parent.js, line 24)

That stateless component class defines a function that calls the passed-down function, and that can take an event object as an argument. (Child.js, lines 10-13)

The stateless component class uses this new function as an event handler. (Child.js, line 20)

When an event is detected, the parent’s state updates. (A user selects a new dropdown menu item)

The stateful component class passes down its state, distinct from the ability to change its state, to a different stateless component. (Parent.js, line 25)

That stateless component class receives the state and displays it. (Sibling.js, lines 5-10)

An instance of the stateful component class is rendered. One stateless child component displays the state, and a different stateless child component displays a way to change the (Parent.js, lines 23-26)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
45
Q

react: Double curly braces is just

A

an object literal inside of the braces that tell jsx to read as javascript

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
46
Q

react: you can set styles by

A

const styles = {background: ‘lightblue’, color: ‘darkred’}

and style={divStyle}

note: Its cool to name the style object according to the element it will be styling

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
47
Q

react: In css style names are written in hyphenated lowercase, in react they are written as

A

camelCase

ie {fontSize: ‘50px’}

note the values are usually strings, but if you don’t use a string, it will assume you are using ‘px’

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
48
Q

react: Its common to keep your styles in a styles file like

A

styles.js

const fontFamily = 'Comic Sans MS, Lucida Handwriting, cursive';
const background = 'pink url("https://media.giphy.com/media/oyr89uTOBNVbG/giphy.gif") fixed';
const fontSize = '4em';
const padding = '45px 0';
const color = 'green';
export const styles = {
  fontFamily: fontFamily,
  background: background,
  fontSize:   fontSize,
  padding:    padding,
  color:      color
};
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
49
Q

react: A presentational component looks like

A

a class with just a render function and a lot of html like JSX, and no ReactDOM.render() function

a container component uses the presentational component, and has a lot of functions

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
50
Q

react: if a component has a lot of functions, it shouldn’t

A

also have a lot of html like JSX

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
51
Q

react: If a component only has a render function, it can be rewritten as a

A

function

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
52
Q

react: To rewrite a stateless presentational component as a function, type

A
class MyComponent extends React.Component {
  render() {
    return ...
  }
}

to (keep it UpperCamelCase)

const MyComponent = () => {
  return ...
}
or if theres a props being passed in
const MyComponent = (props) => {
  return ...
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
53
Q

react: To make a component cause a console warning if a certain prop is not passed in

A

propName: React.PropTypes.string.isRequired,

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
54
Q

react: a propType is

A

a validation you can perform on all of the props passed into a component. Adding this object to the component file after the class declaration.

MyComponent.propTypes = {
    message: React.PropTypes.string,
    style: React.PropTypes.object,
    isMetric: React.PropTypes.bool,
    miles: React.PropTypes.number,
    milesToKM: React.PropTypes.func,
    races: React.PropTypes.array,
}

note: add .isRequired to raise a console error when a prop is not passed in.
ie
message: React.PropTypes.string.isRequired,

Note: This works the same way for functional components

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
55
Q

react: The attributes input field should have are

A

onChange={this.handleChange} value={this.state.inputField}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
56
Q

react: If you call ReactDOM.render() on the same component twice, the mounting lifecycle methods will

A

only run the first time. (except render will rerun if something changes)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
57
Q

react: The updating lifecycle functions are

A

componentWillReceiveProps: Will only run if the component is being passed in props. Needs a nextProps parameter. Opportunity to do something based on the new props a component is going to render. Will become getDerivedStateFromProps.
shouldComponentUpdate: Opportunity to decide whether or not you want a component to update after state change or not by returning true or false. Requires two arguments, nextProps and nextState.
componentWillUpdate: Requires two arguments, nextProps and nextState. It cannot call this.setState(). Meant for doing DOM manipulations outside of react, interacting with an API. Being deprecated.
componentDidUpdate: Requires two arguments, prevProps and prevState, which allows you to compare current to past. Usually call APIs from here.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
58
Q

react: componentWillReceiveProps automatically gets passed one argument called

A

an object called ‘nextProps’ which is the value of the prop that will be passed in

componentWillReceiveProps: function (nextProps) {
console.log(nextProps.text) //will return “Hello world”
}

ReactDOM.render(
-Example text=”Hello world” />, document.getElementById(‘app’)
);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
59
Q

react: To ensure that the component renders properly before the api data returns

A

set up the initial state and default props

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
60
Q

react: componentWillUnmount

A

requires two arguments, prevProps, prevState. Gets called when UI rerenders without this component, or user leaves website or closes their web browser

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
61
Q

rn: You must render your jsx inside

A

View tags -View>-/View>

note: They work like divs

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
62
Q

rn: To use a text input, type

A

-TextInput onChangeText={(text) => {this.setState({name: text})}} />

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
63
Q

rn: To have a scrollable View, you must

A

put ScrollView tags inside View tags

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
64
Q

rn: To make a button, type

A

-Button onPress={this.handleSubmit}>String-/Button>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
65
Q

rn: Styles must be written

A
into a Stylesheet object like 
const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    paddingTop: Constants.statusBarHeight,
    backgroundColor: '#ecf0f1',
  },
  paragraph: {
    marginTop: 24,
  },
});

and then called like style={styles.paragraph}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
66
Q

rn: The events for react native are

A

onPress
onLongPress: press and hold a view for a time
onChangeText: for TextInput changes

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
67
Q

rn: To make an alert, type

A

import { Alert } from ‘react-native’;

in function
Alert.alert(‘alert title’, ‘alert body’)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
68
Q

rn: You cannot access the event object

A

from functions

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
69
Q

rn: To render a list from an API in a press handler, type

A
handlePress() {
  return fetch('https://url.json')
  .then((response) => response.json())
  .then((responseJson) => {
    this.setState({movies: responseJson.itemArray})
  })
}
render() {
  let itemList = this.state.movies.map( (val, key) => {
  return {val.title}
})

{itemList}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
70
Q

react: to make a video component

A

either use this and copy oak, where the video plays in full width which ever orientation your phone is in, over black background, and have a skip button on top right, and clickin on video pauses, it. https://medium.com/@kalen7/build-this-simple-video-player-with-react-native-and-expo-to-tell-a-multi-part-story-part-3-48f3ce1664f6

or use this, but the full screen doesnt work properly.
https://www.youtube.com/watch?v=X-RoXqCoHK0

this guy has a better ui
https://www.youtube.com/watch?v=1WtL1rNOLcg

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
71
Q

react: to make navigation use

A

https: //www.youtube.com/watch?v=_XZqafNubyQ
https: //www.youtube.com/watch?v=5f5VEEmMSyE

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
72
Q

rn: in react native dont forget

A

use Text, and View instead of html tags
import * as React from ‘react’ and
to type: import { Text, View, StyleSheet } from ‘react-native’;
text-transform is not available
padding: ‘20px 40px’, does not work. Use paddingHorizontal and paddingVertical
use button from: import { Button } from ‘react-native-elements’; because it allows for buttonStyle={styles.buttonStyles} and textStyle={styles.textStyles} . Normal button from react-native does not.
use fontWeight: ‘bold’ instead of 700
register new functions in the constructor

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
73
Q

rn: To make a box shadow, type

A

shadowOffset:{ width: 10, height: 10, },
shadowColor: ‘black’,
shadowOpacity: 1.0,
shadowRadius: 7,

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
74
Q

rn: its a bad idea to spread

A

items from top to bottom using margins, I should use column flex items so that it spreads for bigger phones.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
75
Q

rn: To make a ScrollView horizontal, type

A

-ScrollView
horizontal={true}
>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
76
Q

rn: you should not use this.setState() in

A

componentDidMount

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
77
Q

js: To append to end of list in place, type

A

myArray.push(item)

to not do it in place, and actually return a new array use myArray.concat(item)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
78
Q

js: to make a for loop in js, type

A

for (let item of [1,2,3]) {
console.log(item);
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
79
Q

react: It seems registering functions in the constructor is only necessary if you

A

will be sending them as props? Can I attach new functions to self at will if I am using them in the same component? Like, if the function only ever gets called from a neighboring function.

This is an example from React.js website :

  class Timer extends React.Component {
          constructor(props) {
            super(props);
            this.state = { seconds: 0 };
          }
      tick() {
        this.setState(prevState => ({
          seconds: prevState.seconds + 1
        }));
      }

      componentDidMount() {
        this.interval = setInterval(() => this.tick(), 1000);
      }

      componentWillUnmount() {
        clearInterval(this.interval);
      }
          render() {
            return (
              -div>
                Seconds: {this.state.seconds}
              -/div>
            );
          }
        }

ReactDOM.render(, mountNode);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
80
Q

react: It would be convenient to set the whole body of the app to become a

A

spinner if ever a state variable is set to loading when I send an API request so its easier for me to show a spinner when loading by doing this.setState instead of manually

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
81
Q

react: If you name a file index.js

A

you can import it with the path to it, but without writing its actual name

import name from “./folder” // this automatically opens index.js

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
82
Q

redux: The basic steps of redux are

A

You call an action from the component where you originally had the fetch request to get posts.

That action in actions/postActions.js calls the fetch and gets the posts. Then it calls dispatch which sends the return of that fetch into the reducer with a “type” of reducer you want to call

Then the reducer is where you combine the new post data with the initial state (set in the reducer) and then it returns as a ready to use new state.

Then to use that new state in your component, you need to add code to your component that maps the state from the reducer to props, so you can call this.props.itemFromReducerMadeState

the root reducer is just boilerplate

https://youtu.be/93p3LxR9xfM?t=1350

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
83
Q

react: To send a parameter back in an onPress function

A

in element
onPress={e => this.props.onPress(e, ‘param’)}

Note: Learn these functions

in parent
handlePress(e, param1) {
console.log(param1)
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
84
Q

react: You should declare your functions in the constructor to add .bind(this) because

A

using arrow functions (that use the enclosing ‘this’) are less performant/slower.

https: //medium.com/@charpeni/arrow-functions-in-class-properties-might-not-be-as-great-as-we-think-3b3551c440b1
https: //stackoverflow.com/questions/48699573/correct-use-of-arrow-functions-in-react
https: //stackoverflow.com/questions/52571478/how-to-pass-info-from-a-child-component-to-a-function-in-the-parent-component/52571638#52571638

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
85
Q

js: Javascript functions always allow for

A

optional parameters

So if a function expects 3 params, but you send in just one, it run with just the first param

const myFunc = (num1, num2, num3) => { console.log(num1) }

myFunc(55)
> 55

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
86
Q

js: To spread an array to fill in a function’s parameters, type

A

myFunc(…myArray)

note: the old way was
myFunc.apply(null, myArray)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
87
Q

js: To assign all the items in an array into variables in one line, type

(similar to tuple unpacking)

A

let [a,b,c] = [1,2,3]

note: Must declare all of the items, cannot have unequal arrays.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
88
Q

react: Calling setState({num:4}) and then immediately this.state.num might return your previous this.state.num value because

A

setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value. There is no guarantee of synchronous operation of calls to setState and calls may be batched for performance gains.

If you want a function to be executed after the state change occurs, pass it in as a callback.

this.setState({value: event.target.value}, function () {
console.log(this.state.value);
});

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
89
Q

js: cool pattern

A

createTarget(key, ms) {

ms = ms || random(500, 2000);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
90
Q

js: learn

A

how to make functions that take a callback
https://stackoverflow.com/questions/2190850/create-a-custom-callback-in-javascript

and learn how to set default values in a function when params are not sent in.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
91
Q

js: To use setInterval, you need to type

A

let that = this outside of the setInterval because setInterval overrides the ‘this’ from react.

this.incrementer = setInterval(function() {
  that.setState({seconds: that.state.seconds + 1})
  console.log(that.state.seconds)
}, 1000)

or

    let that = this
    let pointer = 0
     let incrementer = setInterval(function() {
      that.setState({ currentNumber: that.state.currentSeries[pointer] })
      pointer += 1
      if (pointer == that.state.currentSeries.length + 1) {
        clearInterval(incrementer)
        that.setState({ currentNumber: '-', gameStatus: 'inputting'})
      }
    }, 1000)

you also need a this.incrementer variable so you can later call clearInterval(this.incrementer)

92
Q

react: When you call setState and you are updating a state property based on an update of a higher up state property, remember

A

it wont work. The all update simultaneously,

ie

this.setState({
first: 1 + 1,
second: this.state.first + 1 //this will not equal 3. It will be the current state of first plus 1.
})

93
Q

node: To reinstall node

A

delete /usr/local/lib/node_modules

download node and npm from their sites

94
Q

rn: StackNavigator

A

Automatically makes the first component you pass into it the default screen.
To use StackNavigator, your render function must have only the StackNavigator component in it, nothing else.

95
Q

rn: To render an image, type

A

-Image source={require(‘./img.png’)} />

96
Q

rn: To run expo on local, type

A

exp init

exp start –ios

97
Q

rn: To render a list of images, seems you must

A

put the require() inside the object array, not pass a path string into require() inside the child component

eventList: [
{ image: require(‘./assets/PARK1.jpg’)},
{ image: require(‘./assets/OXFORD1.jpeg’)}
],

98
Q

rn: To add flex styles to a ScrollView you must

A

create a new style and pass it in as props to the component as contentContainerStyle={styles.contentContainerStyle}

contentContainerStyle: {
alignItems: ‘center’,
justifyContent: ‘center’,
}

99
Q

rn: Unlike css, react native does not have

A

z-index, but you can order your code to achieve the same effect

100
Q

rn: To make an image background

A

note: Image background auto crops nicely, prob use that instead.
note: requires style prop

import * as React from ‘react’
import { StyleSheet, Text, View, Image, ImageBackground } from ‘react-native’;

export class Event extends React.Component {
	render() {
		return (
      -ImageBackground style={styles.imageStyle} source={this.props.source}>
        ...
      -/ImageBackground>
		)
	}
}
const styles = StyleSheet.create({
  imageStyle: {
    flex: 1,
    flexDirection: 'column',
    width: '100%',
    height: 100,
  }
})
101
Q

rn: to make an overlay for an image or semi transparent filter, type

A

import * as React from ‘react’
import { StyleSheet, Text, View, Image, ImageBackground } from ‘react-native’;

export class Event extends React.Component {
	render() {
		return (
	)
} }
const s = StyleSheet.create({
  imageStyle: {
    flex: 1,
    flexDirection: 'column',
    width: '100%',
    height: 200,
  }, 
  overlay: {
    position: 'absolute',
    top: 0,
    right: 0,
    bottom: 0,
    left: 0,
    backgroundColor: 'red',
    opacity: 0.3

}
})

102
Q

css: Seems when you change the flex direction on a flex container, then make another flex container inside, it will

A

also have the same flex direction as the parent.

103
Q

rn: background images with gradients for text

A

import * as React from ‘react’
import { StyleSheet, Text, View, Image, ImageBackground } from ‘react-native’;
import { LinearGradient } from ‘expo’;

export class Event extends React.Component {
	render() {
		return (
      Hey Bro

	)
} }
const styles = StyleSheet.create({
  imageStyle: {
    flex: 1,
    flexDirection: 'column',
    width: '100%',
    height: 200,
  }, 
  overlay: {
    position: 'absolute',
    top: 0,
    right: 0,
    bottom: 0,
    left: 0,
    backgroundColor: 'red',
    opacity: 0.3,
  }, 
  linearGradient: {
    backgroundColor: "transparent",
    position: "absolute",
    top: 0,
    bottom: 0,
    left: 0,
    right: 0,
    flex: 1,
    justifyContent: 'flex-end',
    padding:10,
  },
  textStyle: {
  	color: 'white',
  	fontWeight: 'bold',
  	fontSize: 20
  }
})
104
Q

rn: to do registration

A

https: //www.youtube.com/watch?v=y9B5BOGdqDE
https: //stackoverflow.com/questions/6666267/architecture-for-merging-multiple-user-accounts-together
openid: https://www.youtube.com/watch?v=996OiexHze0

It seems that the way to use oauth with server sessions is:
you get the email from the oath provider,
then create an account on your server, and make the password empty.
Couldn’t someone from the console send a login request with an empty password?

105
Q

oath: oauth gives you an auth code in the browser redirect, and not the access key because

A

someone can see it in your history, logs, or browser window, its a bit less secure, and then the browser gets the secret before anyone can steal it and sends it with the apps id to get the access token first.

106
Q

oath: The way logging in with oauth works is

A

You use openid connect. Like usual, when you ask for the users data, you also ask for their openid and the app will know to send you a bunch of basic data about the user like email and id in a json web token, which can be decoded.

The session key needs to stay on my database, cause we can’t call facebook on every request, too slow and expensive for them.

— old answer
After the user has down their first oauth, they will get logged in with no password and get a session key related to their user record. When they log or the session key expires the session key will disappear. That means we will not know who is sending the request, so we will need to do oauth again to get their email and then log them into our backend again so we can give them back a new session key.

https: //stackoverflow.com/questions/6666267/architecture-for-merging-multiple-user-accounts-together
https: //www.youtube.com/watch?v=996OiexHze0
https: //www.youtube.com/watch?v=y9B5BOGdqDE

107
Q

oauth: Often an access token will be accompanied

A

by a refresh token, that can be used to get a new access token when the initial one expires.

https://stackoverflow.com/questions/7030694/why-do-access-tokens-expire

108
Q

rn: Instead of buttons use

A

https://stackoverflow.com/questions/39123357/when-to-use-touchablenativefeedback-touchablehighlight-or-touchableopacity

TouchableHighlight

  • What it does: Darkens or lightens the background of the element when pressed.
  • When to use it: On iOS for touchable elements or buttons that have a solid shape or background, and on ListView items.

TouchableOpacity

  • What it does: Lightens the opacity of the entire element when pressed.
  • When to use it: On iOS for touchable elements that are standalone text or icons with no background color.

TouchableNativeFeedback (dont use on ios, not supported)

  • What it does: Adds a ripple effect to the background when pressed.
  • When to use it: On Android for almost all touchable elements.
109
Q

sometimes when the simulator is failing yu must

A

file > Reset Content and Settings and reboot comp?

110
Q

js: Async means

A

the async function will start a new thread and will return whenever it is ready, while the script thats calling it will just continue once it initiates the async function

111
Q

js: To make a function with a callback function, type

A
function myFunc(param1, callback) {
  callback()
}

myFunc(‘string’, function(){
console.log(‘string’)
})

112
Q
js: If you write
var myVar = null
function myFunc() {
  var myVar = "string"
}

after you run the function the value of myVar will be

A

null because to reassign the variable you cannot write var again.

113
Q

node: To create a child process in a node script that can send messages from the parent, and listen to messages from the parent

A

Basically:
Start a main process
Spawn a child process in any language and save to an instance variable
Use that variable to create .on(‘data’) event handlers that receive data when the child process prints
If the child process ever listens, you can emit data to it using .write()

Instantiate child process object in order to start running the new process. This runs whatever command is inside spawn in something like a new terminal.
var cp = require("child_process").spawn("./child_script_command", [], {
  detached: false,
  stdio: "pipe"
})
note: Might need to add options to the empty array like this. One guy just passes in 'pipe' and the other uses an array.
https://stackoverflow.com/questions/28946904/piping-data-from-child-to-parent-in-nodejs
https://stackoverflow.com/questions/46195785/how-to-send-to-stdin-and-receive-from-stdout-of-c-program-from-node-js

stdout is like a print() function and stdin is like an input() function

To listen for console.log()/process.stdout.write()/print() calls from the child process, type:

cp.stdout.on(“data”, (data) => {
console.log(“stdout: “ + data);
});

To send a message to to the child process, type something like

child. stdio[3].write(‘My message’)
note: The 3 might be whatever option you passed into the array upon instantiation.

I assume the child process needs to be listening in order to use the child.stdio[3].write(‘My message’) by running a function like pythons input()

https://stackoverflow.com/questions/46195785/how-to-send-to-stdin-and-receive-from-stdout-of-c-program-from-node-js

Note: If the subprocess is also a node script, use ‘fork’ which will spawn new V8 engine.

https: //stackoverflow.com/questions/17861362/node-js-child-process-difference-between-spawn-fork
https: //medium.com/@NorbertdeLangen/communicating-between-nodejs-processes-4e68be42b917
https: //www.youtube.com/watch?v=gQPhH0roJ9s

114
Q

node: console.log() calls

A

process.stdout.write with formatted output

Console.prototype.log = function() {
this._stdout.write(util.format.apply(this, arguments) + ‘\n’);
};

115
Q

node: If a key and a value in an object have the same variable name, you can

A

just write the variable name once, and don’t need a colon.

Note: The variable name must be defined before you call it

116
Q

html: To make a link tag that downloads the source of its href and sets a new name to the file, type

A

download=’file_name.extension’

117
Q

html: To download objects from javascript

A

create a url to it, and make a link with that url as the href, and then add download=’file_name.extension’ to the link

let blob = new Blob(recordedChunks, {type: 'video/webm'})
let url = URL.createObjectURL(blob)
let a = document.createElement('a')
a.href = url
a.download = 'file_name.extension'

note: its good to run this function when finished with a url, so the browser doesn’t have to hold a reference to it.
a.click()
setTimeout(function () {
document.body.removeChild(a)
window.URL.revokeObjectURL(url)
}, 100)
}

118
Q

node: To read and write files, type

A

let fs = require(‘fs’)

fs.readFile(‘filename.txt’, ‘utf8’, (err, data)=>{
console.log(err)
})

fs.writeFile(‘filename.txt’, ‘string’, (err, data)=>{
console.log(err)
}) //note sure what params this callback takes.

Note: writing files requires a callback.
https://www.youtube.com/watch?v=U57kU311-nE

119
Q

node: Nodejs does not currently support

A

importing ES6 modules using
import x from ‘y’

unless you add the –experimental-modules flag

120
Q

node: blob stands for

A

Binary Large Object

121
Q

end to end encryption

A

you generate keys from a passcode. You get one public key and one private key. Only the private key can decrypt files that are encrypted with the public key. So you need to send people your public key, they encrypt with it, and then you decrypt with your private key.

Since the videos only go one way, I need to encrypt them with my referees public key. And then he will decrypt it on his end.

122
Q

cs: a bit is

A

a string of either 0 or 1, and a byte is a string of 8 either 0s or 1s

123
Q

cs: a binary is

A

a string of either 0s or 1s that make up any file.

124
Q

cs: Encryption algorithms encrypt

A

bits. All digital media (text, pictures, videos, etc) is stored as bits at the lowest level, therefore, they can all be encrypted.

125
Q

node: To install a new package locally and add it to “dependencies” in package.json

A

npm install packagename –save

126
Q

ex: To make a basic express server, type

A
const express = require('express')
const app = express()
const router = express.Router();
const bodyParser = require('body-parser')
// app.set('view engine', 'ejs'); for ejs server rendering
// app.set('views', path.join(\_\_dirname, 'views')); for choosing views directory

// app.use(‘/my_namespace’, router); for namespacing urls

app. use(bodyParser.json())
app. use(bodyParser.urlencoded({extended: false})) // false means you cannot post nested object like {name: {id: 2}}

router.get(‘/url/:id’, (req, res) => {
res.send(‘Hello World!’)
// res.json([{id: 1, id: 2}]) for json
// res.render(‘filename’, {id: 1}) render ejs template with passed in vars
})

app. listen(3000, () => console.log(Running))
https: //www.youtube.com/watch?v=gnsO8-xJ8rs

127
Q

js: To add another argument to an event handler function (like below), you can

document.querySelector(‘a’).onclick = (e) => {
console.log(e)
}

A

use a closure, because it will return an anonymous function with just the event argument but your extra argument will be stored in the closure scope and be accessible inside the anonymous function.

function myClosure(myExtraArg) {
  return (e) => {
    console.log(e)
    console.log(myExtraArg)
  }
}

document.querySelector(‘a’).onclick = myClosure(myExtraArg)

128
Q

js: To add another argument to an event handler function (like below), you can NOT

document.querySelector(‘a’).onclick = (e) => {
console.log(e)
}

A

just add an argument to the anonymous function, because it only takes one event parameter.

129
Q

js: Arguments set in .bind() will be

A

prepended to the argument list when you call the resulting function

130
Q

react: functionName(){…}.bind(this)

A

returns a new function that copies the body of the function it is called on and passes in “this” as an argument so you have access to a specific “this” inside the function. Note: This does not call the function.

131
Q

exp: to allow cors, type

A

app.use(function(req, res, next) {
res.header(“Access-Control-Allow-Origin”, ‘*’);
res.header(“Access-Control-Allow-Credentials”, true);
res.header(‘Access-Control-Allow-Methods’, ‘GET,PUT,POST,DELETE,OPTIONS’);
res.header(“Access-Control-Allow-Headers”, ‘Origin,X-Requested-With,Content-Type,Accept,content-type,application/json’);
next();
});

132
Q

i need to learn these terms

A

https://medium.freecodecamp.org/do-you-want-a-better-understanding-of-buffer-in-node-js-check-this-out-2e29de2968e8

133
Q

js: To make a range function like python and use it to map, type

A

const range = n => […Array(n).keys()]

range(5).map(i => (

))

or just use this wherever needed

[…Array(11).keys()]

134
Q

js: javascript packages usually run sequential code by using

like code that needs to run after a value is ready.

A

event handle functions
i.e.

stream. onStop = function() { … }
stream. stop()

135
Q

JS: Promise.all([myPromise1, myPromise2]) passes into the .then()

A

an array with all the resolve values.

i.e.

Promise.all([
  valuePromise1,
  valuePromise2,
  valuePromise3,
]).then((resolveValueArray)=>{
  resolveValueArray.forEach((item)=>{
  ...
  })
})
136
Q

JS: In order to return a value from an arrow function without writing ‘return’, it must

A

be an expression and cannot have a block

so
() => ‘string’ + ‘string’ // is fine
() => {key: ‘value’} // returns undefined, because curly brackets denote a block.
() => ({key: ‘value’}) // brackets make this work
() => myFunc({
key: ‘value’
}) // its also fine for one expression to use multiple lines

137
Q

JS: await must only be used on

A

an expression that returns a promise

138
Q

JS: await must be used

A

in a function marked async
i.e.
async function funcName() {}

or

const foo = async () => {}

139
Q

JS: the difference between async/await and promises is

A

mostly aesthetic. It just cannot wait for multiple promises at the same time.

these are the same:

async function funcName() {
  const varName = await myPromise() //this pauses the function until varName gets the resolve value
  const varName2 = await varName.getName()
  return varName2
}

myPromise().then( (result) => { return result.getName() })

140
Q

js: An async await function always returns

A

a promise

141
Q

js: in order to be able to call .then() on another .then()

i. e. myPromise.then(…).then(…)

A

the prior .then() needs to return a promise.

142
Q

js: A sign your function is doing too much is if

A

you cannot give it a verb name, like checkRegistration(), endRecording()

note: name functions that return booleans with: should, is, can, has

nice style guide https://gist.github.com/rwaldron/793649

https://twitter.com/dvnabbott/status/1067828175399399424

this video has nice styling
his functions have titles formatted like
// -- title --

BE CONSISTENT WITH DOUBLE OR SINGLE QUOTES.

2 spaces after comment

  //  Bad
  if(blah==='foo'){
   foo('bar','baz',{zoo:1});
  }
  //  Good
  if ( blah === "foo" ) {
    foo( "bar", "baz", { zoo: 1 } );
  }  
  var a = true,
      // Bad
      c   = false,
      // Good
      b = false;
  //  Good
  function foo( arg1, argN ) {

}

  //  Bad
  function foo(arg1, argN) {

}

  //  Good
  var a = [ 1, 2, 3, 4 ];
  //  Good
  foo( a[1] );
  //  Exceptions: Functions with callbacks 
  foo(function() { 

});

  //  Functions accepting arrays/objects
  foo([   ]);
  foo({   });  

Use {} instead of new Object(). Use [] instead of new Array().

ALWAYS USE === OVER == (unless the case requires loose type evaluation )

Truthy/Falsy Evaluation: (includes real true & false for explanation purpose)

  var truthy = ("foo" | 1 | true),
      falsy = (false | null | undefined | 0 | "" | NaN);
  //  BAD *
  if ( typeof undef === "undefined" ) {
  }
  // Good
  if ( !("undef" in window) ) {
  }
  //  Bad * 
  if ( falsy === false ) {
  }
  //  Good
  if ( !falsy ) {
  }
  //  Bad
  if ( array.length >= 1 ) {

}

  //  Good
  if ( array.length ) {
    //  evaluates the same as above
  }
  //  Good
  if ( truthy ) {
  }

End of line comments are prohibited.

  1. Variable Declaration
    BAD:
    var foo = "";
    var bar = "";
    var qux;
GOOD:

var foo = "", 
      bar = "", 
      qux;

comments should either be
Single line above the code that is subject

JsDoc style like (note: also right above the code)

/**
* my comment
* is great
*/
function getNumber( param ) {

}

143
Q

JS: How a promise works is,

A

it runs the initial script inside the Promise declaration
new Promise(function(resolve, reject) {
setTimeout(() => resolve(1), 1000); // (*)
}).then(…)
and waits for resolve to be called inside the promise
After resolve is called .then() runs the function you passed in and uses the prior resolve value as the parameters
this .then function returns a promise and it uses the return value of your passed in function as the resolve value
it runs the next .then() or your function can return another promise and it will use the resolve value of that promise to pass into the next .then() function.

note: If you use a regular function to .then() instead of a promise, it will not wait for the return value and will just pass in undefined if its not ready

example using both a regular function return and a promise return

new Promise(( resolve, reject ) => {
  console.log( 'done 1' )
  resolve( '1' )
})
.then(( res ) => {
  return 2
})
.then(( res ) => {
  return new Promise(( resolve, reject ) => { 
    resolve(3)
  })
})

https://javascript.info/promise-chaining

144
Q

the difference between these is

let myPromise = new Promise(( resolve, reject ) => {
  setTimeout(() => {
    console.log( 'done 1' )
    resolve( '1' )
  }, 3000 )
})
myPromise.then(( res ) => {
  return new Promise(( resolve, reject ) => {
    setTimeout(() => {
      console.log( 'done 2' )
      resolve( '2' )
    }, 3000 )
  })
})

myPromise.then(( res ) => {
console.log( ‘dd’, res ) // prints out 2
})

let myPromise = new Promise(( resolve, reject ) => {
  setTimeout(() => {
    console.log( 'done 1' )
    resolve( '1' )
  }, 3000 )
})
.then(( res ) => {
  return new Promise(( resolve, reject ) => {
    setTimeout(() => {
      console.log( 'done 2' )
      resolve( '2' )
    }, 3000 )
  })
})
.then(( res ) => {
  console.log( 'dd', res ) // prints out 2
})
A

the first one will have 2 promises waiting on the first one in parallel

the second will run sequentially

145
Q

JS: if you do this, the .then functions will run

let myPromise = new Promise(function(resolve, reject) {
  setTimeout(() => resolve(1), 1000);
});

myPromise.then(function(result) {
alert(result); // 1
return result * 2;
});

myPromise.then(function(result) {
alert(result); // 1
return result * 2;
});

myPromise.then(function(result) {
alert(result); // 1
return result * 2;
});

A

in parallel when resolve() is called in the promise

146
Q

js: to run an anonymous function without assigning it anything, type

A

(function() {

})()

or

(() => {

})()

147
Q

js: The stack is

A

the list of all the nested functions that are running

so if you are calling a function inside a function it will be

[
innerFunc2
innerFun1
main
]

and it runs the functions from the top down.

https://youtu.be/8aGhZQkoFbQ?t=869

148
Q

js: If you set setTimeout(…, 0 ) to zero, you are actually

A

deferring running that function until the call stack is clear. That function gets held in the task queue until the call stack is clear, then the ‘event loop’ pushes it onto the call stack. A node script it like having a main.js function that has functions nested in it. setTimeout and fetch are handled by webapis, not processes.
https://youtu.be/8aGhZQkoFbQ?t=869

149
Q

js: To call resolve or reject from outside the new Promise()

A

never mind, you should never do this because it would create possibility for an error from somewhere else to stop the resolve or reject from every firing.

150
Q

js: to mix js with ts you can

A

https://stackoverflow.com/questions/49640121/mixing-javascript-and-typescript-in-node-js

151
Q

js: The similarities and differences between the session cookies and jwt tokens

A

Session cookies only hold the ‘secure attribute’ like the user id. JWTs contain all of the user data, or potentially even all the data a user is allowed to see, so you don’t have to hit the database for much information.

Using session cookies requires checking a sessions table on every request see if that session key is active, and then requires you to check the database again for more user data. JWTs keep everything in the token.

It seems clear that you cant stop someone from executing JS they shouldn’t be, you can only stop them from seeing data they shouldn’t.

Anyone can decode a JWT, but if they try to change any of the claims, the signature will not match the secret, so claims can be trusted.
https://stackoverflow.com/questions/39007335/jwt-how-much-i-can-trust-to-my-payloads

Session cookies are sent to server with every request, while JWTs are recommended to be stored in localstorage and only be sent to protected routes. (routes that require authentication.)
https://stackoverflow.com/questions/51478660/how-to-send-jwt-along-with-every-request-after-successful-login

https://stackoverflow.com/questions/1855422/what-should-be-stored-in-a-session-and-what-in-a-cookie

152
Q

js: Session cookies and jwt tokens are both

A

signed by a secret key held on the server before being set on the browser, and they’re decrypted on every request to ensure that it was originally created by the server. I think the session cookie contains the user id aka the ‘secure attribute’. JWTs have a ‘verify token’ that ensures it was signed by the servers secret key.

if they try to change any of the claims, the signature will not match the secret, so claims can be trusted.
https://stackoverflow.com/questions/39007335/jwt-how-much-i-can-trust-to-my-payloads

153
Q

js: the JWT payload is a

A

JSON string encoded as Base64. So it’s not suitable for storing sensitive details such as passwords.

154
Q

js: Signed tokens allow the server to

A

perform stateless authentication, that is, tell who the user is by just checking the access token content. The server won’t depend on external services to authenticate the user.

155
Q

JWT tokens should be signed with a

A

strong cryptographic key (that must be kept secure on the server) and the signature must be checked before trusting the token.

156
Q

It doesn’t seem that important for access tokens to

A

expire. The user will just be logged in until they log out.

157
Q

The difference between signing and encrypting is

A

When encrypting, you use their public key to write message and they use their private key to read it.

When signing, you use your private key to write message’s signature, and they use your public key to check if it’s really yours.

I want to use my private key to generate messages so only I can possibly be the sender.

I want my public key to be used to read the messages and I do not care who reads them

This is signing, it is done with your private key.

I want to be able to encrypt certain information and use it as a product-key for my software.

I only care that I am the only one who can generate these.

If you only need to know it to yourself, you don’t need to mess with keys to do this. You may just generate random data and keep it in a database.

But if you want people to know that the keys are really yours, you need to generate random data, keep in it a database AND sign it with your key.

I would like to include my public key in my software to decrypt/read the signature of the key

You’ll probably need to purchase a certificate for your public key from a commercial provider like Verisign or Thawte, so that people may check that no one had forged you software and replaced your public key with their.

158
Q

node: To convert a blob to a file, type

A
function blobToFile(theBlob, fileName){
    //A Blob() is almost a File() - it's just missing the two properties below which we will add
    theBlob.lastModifiedDate = new Date();
    theBlob.name = fileName;
    return theBlob;
}

https: //stackoverflow.com/questions/27159179/how-to-convert-blob-to-file-in-javascript/29390393
https: //stackoverflow.com/questions/27159179/how-to-convert-blob-to-file-in-javascript/29390393

159
Q

js: You can combine chunks of a video by

A

adding each chunk to an array whenever the ondataavailable event gets triggered and then use let blob = new Blob(recordedChunks, {type: ‘video/webm’}) to squish them all together.

https: //developer.mozilla.org/en-US/docs/Web/API/MediaRecorder/ondataavailable
https: //jsfiddle.net/f8Lhxn53/
note: var blob = new Blob(chunks, { ‘type’ : ‘audio/ogg; codecs=opus’ }); for audio

160
Q

to make placeholder icons, use

A

https://icons8.com/iconizer

161
Q

using an event function like this and using let is ok because

document.onclick = (e) => {

  let xClick = e.clientX
  let yClick = e.clientY

alert(xClick+ yClick)

}

A

the let variables get deleted after the function is done running

doing multiple runs of the same function is not like calling the let multiple times in the same script

162
Q

react: To make one on change method for all the fields of a form, type

A
change(e) {
  this.setState({
    [e.target.name]: e.target.value,
  })
}
163
Q

if you use http instead of https

A

people will be able to read (sniff) my requests.

164
Q

json: remember no

A

trailing commas in json (confirm this)

165
Q

js: To install a package locally and also add it to “devDependencies” in package.json, type

A

npm install package-name –save-dev

166
Q

js: To uninstall a local node package and remove it from “dependencies” in package.json, type

A

npm uninstall package-name –save

167
Q

js: To uninstall a global node package, type

A

npm uninstall package-name –global

168
Q

js: To generate package.json, type

A

npm init

169
Q

js: package-lock.json is

A

a file automatically generated when you run any npm commands that changes node_modules or package.json. It records the exact version of each dependency and the dependencies of the dependencies. With package.json you can’t control the versions of the dependencies dependencies.

Commit package-lock.json to git, but some say don’t.

https: //stackoverflow.com/questions/51203500/difference-between-package-json-package-lock-json-and-yarn-lock-files
https: //stackoverflow.com/questions/46164194/what-is-the-point-of-putting-npms-package-lock-json-under-version-control

170
Q

js: npm install package-name –global saves the package to

A

/usr/local/lib/node_modules

171
Q

js: npm install package-name (no –global flag) saves the package to

A

/node_modules in current directory. Will create /node_modules if there isn’t one.

172
Q

js: when there is an event handler on a child element and another on a parent element, to only to trigger the child’s event handler, type

A

event.stopPropagation() in the child’s event handler

173
Q

when there is an event handler on a child element and another on a parent element, to only to trigger the child’s event handler, the event handler that gets triggered first is the

A

child’s

174
Q

js: Arrow functions do not have

A

their own ‘this’. The ‘this’ value of the enclosing context is used.

175
Q

js: class fields (variables declared in a class but outside the constructor) are

A

still experimental

176
Q

js: The convention for constructor function names is to

A

CamelCase

https://www.youtube.com/watch?v=7oNWNlMrkpc

177
Q

js: To make an instance of a constructor function you must use

A

the new keyword

let myInstance = new ConstructorFuncName(“string”)

https://www.youtube.com/watch?v=7oNWNlMrkpc

178
Q

js: The two ways to add a function to a constructor function are

A
function MyConstructorFunc() { 
  this.myFunc = function () {
    return 'string'
  }
}

or from outside the constructor

function MyConstructorFunc() {
}

MyConstructorFunc.prototype = function() {
return ‘string’
}

https://www.youtube.com/watch?v=7oNWNlMrkpc

179
Q

js: If you call a function on a constructor functions instance and it cannot find it in that instances declared properties

A

it will look for it in that objects inherited prototype (which is the function object’s declared functions) and if it cannot find it there, it will continue up the prototype chain to the master Object’s declared properties.

https://youtu.be/7oNWNlMrkpc?t=510

180
Q

js: A constructor function can be declared like

A
let MyConstructorFunc = function () {}
and 
function MyConstructorFunc() {}
181
Q

js: A constructor functions instance inherits from

A

the Function object, and that inherits from the master Object.

182
Q

The difference between these two ways to add a function to a constructor is

function MyConstructorFunc() { 
  this.myFunc = function () {
    return 'string'
  }
}
function MyConstructorFunc() {
}

MyConstructorFunc.prototype = function() {
return ‘string’
}

A

instances made from the top one will have the function copied into the instance itself, so when called it will not need to look to the prototype chain, while the second one will need to look up the prototype chain to the constructor function and use the function from there. This allows objects to be smaller because you can keep their shared functions only in the constructor.

183
Q

js: On js instances, the __proto__ property is effectively the

A

parent object

184
Q

js: An instance of a constructor cannot

A

be a constructor too

185
Q

js: in order for constructor functions properties to get copied to the instance, they must use

A

this.

this.propertyName = function() {}
or
this.propertyName = 5

this does not get transferred
propertyName = function() {}

186
Q

a good testing api is

A

jsonplaceholder

187
Q

redux: To install redux

A

npm install redux react-redux redux-thunk
import { Provider } from ‘react-redux’
Wrap the whole return of the render function with -Provider store={store}>…app jsx -/Provider>
‘store’ will hold the state of entire app
above the component add import store from ‘./store’

188
Q
js: if you set
let myVar = {a: 1, b: 2, c: 3}

{…myVar, c: 4} will return

A

{a: 1, b: 2, c: 4}

189
Q

js: To add an item to the beginning of an array, type

A

[].unshift(item)

190
Q

js: To add an item to the end of an array, type

A

[].push(item)

191
Q

react: to import a css stylesheet into a component, type

A

import ‘./ComponentName.css’;

192
Q

react: dont name react project

A

something that might be a package

193
Q

react: componentWillMount has been deprecated, use

A

componentDidMount instead

194
Q

react: componentWillReceiveProps is deprecated, use

A

static getDerivedStateFromProps(nextProps, prevState) instead

https://hackernoon.com/replacing-componentwillreceiveprops-with-getderivedstatefromprops-c3956f7ce607

195
Q

redux: these guys name their reducer files

A

the same as what they will call its key in rooReducer so they can { reducerName, reducerName2 } without colons https://redux.js.org/basics/exampletodolist

I should probably name my reducers they way they do, and not put reducer in the name

196
Q

js: { …[‘a’, ‘b’, ‘c’] } will return

A

{ 0: ‘a’, 1: ‘b’, 3: ‘c’ }

197
Q

js: Array(3) will return

A

[undefined, undefined, undefined]

198
Q

js: to get the keys of an array or object, type

A

.keys()

199
Q

to integrate django with react

A

https://medium.com/netscape/full-stack-django-quick-start-with-jwt-auth-and-react-redux-part-i-37853685ab57

200
Q

node: To send formdata from node and then access it from django, type

A
let formData = {hello: 'there'}
request.post({
  url:'http://127.0.0.1:8000/start/', 
  formData: formData
}, (err, httpResponse, body) => {
  if (err) {
    return console.error('upload failed:', err);
   }
  console.log('body);
});

request.POST[‘hello’]

201
Q

When choosing between let and const ask myself

A

Will I ever be writing myVar = something else

202
Q

i should name functions

A

whatever they return, or if side effects, whatever they do.

203
Q

before I write a function, i need to

A

write a comment about the functionality i need.

204
Q

to see if a package is pure node, type

A

find node_modules/ | grep binding.gyp || echo pure

205
Q

Buffer is not

A

available in javascript, only in node. Javascript uses ArrayBuffer

206
Q

this returns

for(var i = 0; i < 10; i++) { 
 setTimeout(function() { 
   console.log(i); 
   }, 100); 
 }
A

10 ten times

207
Q

js: To create a promise without immediately running it o load

A

wrap it in a function that returns your promise and to start the promise call the function

const myPromiseFunc = () => {
  return new Promise((resolve, reject) => {...})
}

myPromiseFunc().then()

208
Q

js: the best way to make promises is

A

as the return of a function

209
Q

js: In javascript, trailing commas are

A

allowed

210
Q

js: In JSON, trailing commas are

A

not allowed

211
Q

when using fetch to send json, remember to

A

body: JSON.stringify({key: ‘string}),
headers: new Headers({
‘Accept’: ‘application/json’,
‘Content-Type’: ‘application/json’
}),

212
Q

The two main types of post requests

A

json, and x-www-form-urlencoded

If you do not add any headers to fetch, it assumes it is x-www-form-urlencoded.

if using the default x-www-form-urlencoded, you must use
    let formData = new FormData();
    formData.append("key", "value");
fetch(`http://127.0.0.1:8000/upload_screenshot/`, {
  body: formData,

Only x-www-form-urlencoded allows for files, so you must use formdata for files.
DRF wants you to access the request using request.data

To use a json post request, you must use
body: JSON.stringify({key: ‘string}),
headers: new Headers({
‘Accept’: ‘application/json, text/plain, /’,
‘Content-Type’: ‘application/json’
}),

213
Q

by commenting in what a function will do i

A

limit its scope and make it cleaner, by having the name represent what it actually does

214
Q
this code will return
const startWorkSession = (param) => () => { return param } 
startWorkSession('string')()
A

Note: chaining arrow functions works and doesn’t require adding any more brackets

const funcName = () => () => () => console.log(‘string’)

215
Q

js: this code with return
let myVar = () => this
myVar()

A

the window object, if its not in any other object

216
Q

js: Putting brackets around an anonymous function allows you to

( (param) => console.log(param) )(‘string’)

A

call it and pass in params.
You may choose this over declaring variables because the alternative to this code
( (param) = >console.log(param) )(‘string’) will log ‘string’
is
const myFunc = (param) => console.log(param)
myFunc(‘string’)
but it requires declaring myFunc

https://medium.com/@jochasinga/context-smuggle-with-injection-6f38e0ae478e

217
Q

js: An alternative to: let that = this, is

A
var myFunc = (function(that) {
  return function() {
    console.log(that.data);
  }
})(this);
218
Q

in json Whitespace (Space, Horizontal tab, Line feed or New line or Carriage return) outside of quotes

A

does not matter. Trailing commas are not allowed.

219
Q

redux: to write a reducer, type

A

import { FETCH_POSTS, CREATE_POST } from ‘../actions/types’

const initialState = {
items: [],
items2: []
}

export default function (state = initialState, action) {
switch (action.type) {
case FETCH_POSTS:
return {…state, items: action.payload}
case CREATE_POST:
return {…state, items2: [{id:30, title: ‘joiji’}, …state.items]}
default:
return state
}
}

220
Q

to create a function that you call on a class instead of on an instance, type

A

static funcName() {}

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/static

221
Q

python: in requests.get() the difference between the data={} argument and the params={} argument is

A

params make the query string in the URL, data is used to fills body of a request.
note: Get requests should not have a body.

222
Q

on mobile if I want an element to stick to the bottom

A

i need to use a fixed element, because if I just rely on the viewport height, it gets covered by the browsers bottom nav bar

223
Q

great css variables tutorial

A

https://www.youtube.com/watch?v=sQUB039MG0I

224
Q

to make a space between grid columns, type

A

grid-gap:10px;

225
Q

to be able to use a css variable with a number, type

A

–my-var: 20;

width: calc(var(20) * 1px);

226
Q

to have css target a sibling, type

A

~

227
Q

RN: To allow user to unfocus a TextInput by clicking outside the input,

A

Use a ScrollView as the wrapper div instead of a View

https://stackoverflow.com/questions/43431896/unfocus-a-textinput-in-react-native