react Flashcards
react: In jsx, to write a css class attribute, you must write
className=”cssClass”
react: A component “mounting” means
it is rendering for the first time
react: The three mounting methods that get called in order when you call ReactDOM.render() are
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
react: componentDidMount only gets called
AFTER the very first rendering of a component. Using set interval to run ReactDOM.render() again will not retrigger it.
react: componentWillReceiveProps will only get called if
a component is being passed in props
react: componentWillReceiveProps automatically gets passed one argument which is
an object called ‘nextProps’ which is the value of the prop that will be passed in
react: componentWillReceiveProps is an opportunity to
do something based on the new props a component is going use before render
react: files with jsx written in them must be
compiled before sent to browser
react: If a JSX snippet takes up multiple lines, you must
wrap it in parentheses.
react: JSX must be
wrapped in one outermost element.
react: ReactDOM.render() takes the arguments
component and location to inject it
ie
ReactDOM.render(-h1>Hello world-/h1>, document.getElementById(‘app’));
react: To render a JSX expression into the template, type
ReactDOM.render(-h1>Hello world-/h1>, document.getElementById(‘app’));
react: if you call
ReactDOM.render(hello, document.getElementById(‘app’));
and then again
ReactDOM.render(hello, document.getElementById(‘app’));
it will
do nothing because react will only render the same component in the same location again if it has changed
react: In JSX, self closing tags like input and img must
have a closing slack ie img />
react: To evaluate code inside of JSX,
wrap it in {} ie -h1>{2 + 3}-/h1> and the return will be rendered
react: The JSX in your file can access
all the variables in the environment
const theBestString = ‘tralalalala i am da best’;
ReactDOM.render(-h1>{theBestString}-/h1>…
react: event listeners (like onclick) in JSX must
be written in camelCase
onClick={funcName}
react: To manipulate the element that sent an event, use
function functionName(e) { const element = e.target }
ie the -img> src will change.
function changeImage(e) { e.target.setAttribute('src', 'https://url.com'); }
react: in JSX, you cannot
write if statements in the {} braces
js: To write a ternary, type
x > 10 ? y : z
js: To write a conditional using &&, type
x > 10 && functionName()
note: It is the same as a ternary but with no else
React: JSX can be rendered even if it is a
list of JSX objects.
const liArray = [ -li>item 1-/li>, -li>item 2-/li>, -/li>item 3-/li> ];
-ul>{liArray}-/ul>
React: To use map to make a list of JSX objects, type
const myJSXArray = myArray.map((item, key) => -li key={key}>{item}-/li> );
React: The steps for rendering JSX are
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.
js: Class and Component names must be written in
UpperCamelCase
js: importing and exporting modules
https://www.youtube.com/watch?v=Jqn_wjkSZwo
js: To import a file from a filepath instead of from the environment,
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
js: To export something from your file (aka named export), type
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
React: When sending in props to a component, the values that are not strings must
be in {} curly braces
React: When passing an event handler function into a component as a prop, name the prop
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.
React: The name convention for naming event handler functions is
handleClick, handleMouseOver etc.
react: If a component has more than one child between its JSX tags, then
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.
react: To give a component default props that will get called if this.props.propName was called but never passed in, type
class MyComponent extends React.Component { render() { return -h1>{this.props.text}-/h1>; } }
MyComponent.defaultProps = { text: ‘string’ };
react: To create a constructor and set initial state, type
constructor(props) {
super(props);
this.state = { mood: ‘decent’ };
}
ES6: In between functions of a class
do not put a comma
react: whenever you define an event handler that uses this, you must
add this.methodName = this.methodName.bind(this) to your constructor function.
react: this.setState automatically
calls render
react: Stateless child components should only
update a parent component using a function the parent passed down to it through props
react: To choose which component to add ReactDOM.render() to, you need to choose
the highest level one, which calls all the other components in its render function
react: A component should use state to store
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.
react: Every event handler automatically passes in
an event argument into the function
onClick = {this.props.onClick}
in the parent function you can write
handleClick(e) { let value = e.target.value }
react: When an event is happening in a child component, that will then change a parent components state, often
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
react: if you are repeating {this.props.propName} in the render function a lot, might as well
create a variable let propName = this.props.propName in the render function and just use {propName}
react: a common pattern is
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)
react: Double curly braces is just
an object literal inside of the braces that tell jsx to read as javascript
react: you can set styles by
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
react: In css style names are written in hyphenated lowercase, in react they are written as
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’
react: Its common to keep your styles in a styles file like
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 };
react: A presentational component looks like
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
react: if a component has a lot of functions, it shouldn’t
also have a lot of html like JSX
react: If a component only has a render function, it can be rewritten as a
function
react: To rewrite a stateless presentational component as a function, type
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 ... }
react: To make a component cause a console warning if a certain prop is not passed in
propName: React.PropTypes.string.isRequired,
react: a propType is
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
react: The attributes input field should have are
onChange={this.handleChange} value={this.state.inputField}
react: If you call ReactDOM.render() on the same component twice, the mounting lifecycle methods will
only run the first time. (except render will rerun if something changes)
react: The updating lifecycle functions are
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.
react: componentWillReceiveProps automatically gets passed one argument called
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’)
);
react: To ensure that the component renders properly before the api data returns
set up the initial state and default props
react: componentWillUnmount
requires two arguments, prevProps, prevState. Gets called when UI rerenders without this component, or user leaves website or closes their web browser
rn: You must render your jsx inside
View tags -View>-/View>
note: They work like divs
rn: To use a text input, type
-TextInput onChangeText={(text) => {this.setState({name: text})}} />
rn: To have a scrollable View, you must
put ScrollView tags inside View tags
rn: To make a button, type
-Button onPress={this.handleSubmit}>String-/Button>
rn: Styles must be written
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}
rn: The events for react native are
onPress
onLongPress: press and hold a view for a time
onChangeText: for TextInput changes
rn: To make an alert, type
import { Alert } from ‘react-native’;
in function
Alert.alert(‘alert title’, ‘alert body’)
rn: You cannot access the event object
from functions
rn: To render a list from an API in a press handler, type
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}
react: to make a video component
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
react: to make navigation use
https: //www.youtube.com/watch?v=_XZqafNubyQ
https: //www.youtube.com/watch?v=5f5VEEmMSyE
rn: in react native dont forget
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
rn: To make a box shadow, type
shadowOffset:{ width: 10, height: 10, },
shadowColor: ‘black’,
shadowOpacity: 1.0,
shadowRadius: 7,
rn: its a bad idea to spread
items from top to bottom using margins, I should use column flex items so that it spreads for bigger phones.
rn: To make a ScrollView horizontal, type
-ScrollView
horizontal={true}
>
rn: you should not use this.setState() in
componentDidMount
js: To append to end of list in place, type
myArray.push(item)
to not do it in place, and actually return a new array use myArray.concat(item)
js: to make a for loop in js, type
for (let item of [1,2,3]) {
console.log(item);
}
react: It seems registering functions in the constructor is only necessary if you
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);
react: It would be convenient to set the whole body of the app to become 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
react: If you name a file index.js
you can import it with the path to it, but without writing its actual name
import name from “./folder” // this automatically opens index.js
redux: The basic steps of redux are
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
react: To send a parameter back in an onPress function
in element
onPress={e => this.props.onPress(e, ‘param’)}
Note: Learn these functions
in parent
handlePress(e, param1) {
console.log(param1)
}
react: You should declare your functions in the constructor to add .bind(this) because
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
js: Javascript functions always allow for
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
js: To spread an array to fill in a function’s parameters, type
myFunc(…myArray)
note: the old way was
myFunc.apply(null, myArray)
js: To assign all the items in an array into variables in one line, type
(similar to tuple unpacking)
let [a,b,c] = [1,2,3]
note: Must declare all of the items, cannot have unequal arrays.
react: Calling setState({num:4}) and then immediately this.state.num might return your previous this.state.num value because
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);
});
js: cool pattern
createTarget(key, ms) {
ms = ms || random(500, 2000);
js: learn
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.
js: To use setInterval, you need to type
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)
react: When you call setState and you are updating a state property based on an update of a higher up state property, remember
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.
})
node: To reinstall node
delete /usr/local/lib/node_modules
download node and npm from their sites
rn: StackNavigator
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.
rn: To render an image, type
-Image source={require(‘./img.png’)} />
rn: To run expo on local, type
exp init
exp start –ios
rn: To render a list of images, seems you must
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’)}
],
rn: To add flex styles to a ScrollView you must
create a new style and pass it in as props to the component as contentContainerStyle={styles.contentContainerStyle}
contentContainerStyle: {
alignItems: ‘center’,
justifyContent: ‘center’,
}
rn: Unlike css, react native does not have
z-index, but you can order your code to achieve the same effect
rn: To make an image background
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, } })
rn: to make an overlay for an image or semi transparent filter, type
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
}
})
css: Seems when you change the flex direction on a flex container, then make another flex container inside, it will
also have the same flex direction as the parent.
rn: background images with gradients for text
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 } })
rn: to do registration
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?
oath: oauth gives you an auth code in the browser redirect, and not the access key because
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.
oath: The way logging in with oauth works is
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
oauth: Often an access token will be accompanied
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
rn: Instead of buttons use
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.
sometimes when the simulator is failing yu must
file > Reset Content and Settings and reboot comp?
js: Async means
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
js: To make a function with a callback function, type
function myFunc(param1, callback) { callback() }
myFunc(‘string’, function(){
console.log(‘string’)
})
js: If you write var myVar = null
function myFunc() { var myVar = "string" }
after you run the function the value of myVar will be
null because to reassign the variable you cannot write var again.
node: To create a child process in a node script that can send messages from the parent, and listen to messages from the parent
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
node: console.log() calls
process.stdout.write with formatted output
Console.prototype.log = function() {
this._stdout.write(util.format.apply(this, arguments) + ‘\n’);
};
node: If a key and a value in an object have the same variable name, you can
just write the variable name once, and don’t need a colon.
Note: The variable name must be defined before you call it
html: To make a link tag that downloads the source of its href and sets a new name to the file, type
download=’file_name.extension’
html: To download objects from javascript
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)
}
node: To read and write files, type
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
node: Nodejs does not currently support
importing ES6 modules using
import x from ‘y’
unless you add the –experimental-modules flag
node: blob stands for
Binary Large Object
end to end encryption
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.
cs: a bit is
a string of either 0 or 1, and a byte is a string of 8 either 0s or 1s
cs: a binary is
a string of either 0s or 1s that make up any file.
cs: Encryption algorithms encrypt
bits. All digital media (text, pictures, videos, etc) is stored as bits at the lowest level, therefore, they can all be encrypted.
node: To install a new package locally and add it to “dependencies” in package.json
npm install packagename –save
ex: To make a basic express server, type
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
js: To add another argument to an event handler function (like below), you can
document.querySelector(‘a’).onclick = (e) => {
console.log(e)
}
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)
js: To add another argument to an event handler function (like below), you can NOT
document.querySelector(‘a’).onclick = (e) => {
console.log(e)
}
just add an argument to the anonymous function, because it only takes one event parameter.
js: Arguments set in .bind() will be
prepended to the argument list when you call the resulting function
react: functionName(){…}.bind(this)
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.
exp: to allow cors, type
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();
});
i need to learn these terms
https://medium.freecodecamp.org/do-you-want-a-better-understanding-of-buffer-in-node-js-check-this-out-2e29de2968e8
js: To make a range function like python and use it to map, type
const range = n => […Array(n).keys()]
range(5).map(i => (
…
))
or just use this wherever needed
[…Array(11).keys()]
js: javascript packages usually run sequential code by using
like code that needs to run after a value is ready.
event handle functions
i.e.
stream. onStop = function() { … }
stream. stop()
JS: Promise.all([myPromise1, myPromise2]) passes into the .then()
an array with all the resolve values.
i.e.
Promise.all([ valuePromise1, valuePromise2, valuePromise3, ]).then((resolveValueArray)=>{ resolveValueArray.forEach((item)=>{ ... }) })
JS: In order to return a value from an arrow function without writing ‘return’, it must
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
JS: await must only be used on
an expression that returns a promise
JS: await must be used
in a function marked async
i.e.
async function funcName() {}
or
const foo = async () => {}
JS: the difference between async/await and promises is
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() })
js: An async await function always returns
a promise
js: in order to be able to call .then() on another .then()
i. e. myPromise.then(…).then(…)
the prior .then() needs to return a promise.
js: A sign your function is doing too much is if
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.
- 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 ) {
}
JS: How a promise works is,
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
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 })
the first one will have 2 promises waiting on the first one in parallel
the second will run sequentially
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;
});
in parallel when resolve() is called in the promise
js: to run an anonymous function without assigning it anything, type
(function() {
…
})()
or
(() => {
…
})()
js: The stack is
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
js: If you set setTimeout(…, 0 ) to zero, you are actually
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
js: To call resolve or reject from outside the new Promise()
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.
js: to mix js with ts you can
https://stackoverflow.com/questions/49640121/mixing-javascript-and-typescript-in-node-js
js: The similarities and differences between the session cookies and jwt tokens
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
js: Session cookies and jwt tokens are both
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
js: the JWT payload is a
JSON string encoded as Base64. So it’s not suitable for storing sensitive details such as passwords.
js: Signed tokens allow the server to
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.
JWT tokens should be signed with a
strong cryptographic key (that must be kept secure on the server) and the signature must be checked before trusting the token.
It doesn’t seem that important for access tokens to
expire. The user will just be logged in until they log out.
The difference between signing and encrypting is
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.
node: To convert a blob to a file, type
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
js: You can combine chunks of a video by
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
to make placeholder icons, use
https://icons8.com/iconizer
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)
}
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
react: To make one on change method for all the fields of a form, type
change(e) { this.setState({ [e.target.name]: e.target.value, }) }
if you use http instead of https
people will be able to read (sniff) my requests.
json: remember no
trailing commas in json (confirm this)
js: To install a package locally and also add it to “devDependencies” in package.json, type
npm install package-name –save-dev
js: To uninstall a local node package and remove it from “dependencies” in package.json, type
npm uninstall package-name –save
js: To uninstall a global node package, type
npm uninstall package-name –global
js: To generate package.json, type
npm init
js: package-lock.json is
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
js: npm install package-name –global saves the package to
/usr/local/lib/node_modules
js: npm install package-name (no –global flag) saves the package to
/node_modules in current directory. Will create /node_modules if there isn’t one.
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
event.stopPropagation() in the child’s event handler
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
child’s
js: Arrow functions do not have
their own ‘this’. The ‘this’ value of the enclosing context is used.
js: class fields (variables declared in a class but outside the constructor) are
still experimental
js: The convention for constructor function names is to
CamelCase
https://www.youtube.com/watch?v=7oNWNlMrkpc
js: To make an instance of a constructor function you must use
the new keyword
let myInstance = new ConstructorFuncName(“string”)
https://www.youtube.com/watch?v=7oNWNlMrkpc
js: The two ways to add a function to a constructor function are
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
js: If you call a function on a constructor functions instance and it cannot find it in that instances declared properties
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
js: A constructor function can be declared like
let MyConstructorFunc = function () {} and function MyConstructorFunc() {}
js: A constructor functions instance inherits from
the Function object, and that inherits from the master Object.
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’
}
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.
js: On js instances, the __proto__ property is effectively the
parent object
js: An instance of a constructor cannot
be a constructor too
js: in order for constructor functions properties to get copied to the instance, they must use
this.
this.propertyName = function() {}
or
this.propertyName = 5
this does not get transferred
propertyName = function() {}
a good testing api is
jsonplaceholder
redux: To install redux
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’
js: if you set let myVar = {a: 1, b: 2, c: 3}
{…myVar, c: 4} will return
{a: 1, b: 2, c: 4}
js: To add an item to the beginning of an array, type
[].unshift(item)
js: To add an item to the end of an array, type
[].push(item)
react: to import a css stylesheet into a component, type
import ‘./ComponentName.css’;
react: dont name react project
something that might be a package
react: componentWillMount has been deprecated, use
componentDidMount instead
react: componentWillReceiveProps is deprecated, use
static getDerivedStateFromProps(nextProps, prevState) instead
https://hackernoon.com/replacing-componentwillreceiveprops-with-getderivedstatefromprops-c3956f7ce607
redux: these guys name their reducer files
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
js: { …[‘a’, ‘b’, ‘c’] } will return
{ 0: ‘a’, 1: ‘b’, 3: ‘c’ }
js: Array(3) will return
[undefined, undefined, undefined]
js: to get the keys of an array or object, type
.keys()
to integrate django with react
https://medium.com/netscape/full-stack-django-quick-start-with-jwt-auth-and-react-redux-part-i-37853685ab57
node: To send formdata from node and then access it from django, type
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’]
When choosing between let and const ask myself
Will I ever be writing myVar = something else
i should name functions
whatever they return, or if side effects, whatever they do.
before I write a function, i need to
write a comment about the functionality i need.
to see if a package is pure node, type
find node_modules/ | grep binding.gyp || echo pure
Buffer is not
available in javascript, only in node. Javascript uses ArrayBuffer
this returns
for(var i = 0; i < 10; i++) { setTimeout(function() { console.log(i); }, 100); }
10 ten times
js: To create a promise without immediately running it o load
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()
js: the best way to make promises is
as the return of a function
js: In javascript, trailing commas are
allowed
js: In JSON, trailing commas are
not allowed
when using fetch to send json, remember to
body: JSON.stringify({key: ‘string}),
headers: new Headers({
‘Accept’: ‘application/json’,
‘Content-Type’: ‘application/json’
}),
The two main types of post requests
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’
}),
by commenting in what a function will do i
limit its scope and make it cleaner, by having the name represent what it actually does
this code will return const startWorkSession = (param) => () => { return param } startWorkSession('string')()
Note: chaining arrow functions works and doesn’t require adding any more brackets
const funcName = () => () => () => console.log(‘string’)
js: this code with return
let myVar = () => this
myVar()
the window object, if its not in any other object
js: Putting brackets around an anonymous function allows you to
( (param) => console.log(param) )(‘string’)
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
js: An alternative to: let that = this, is
var myFunc = (function(that) { return function() { console.log(that.data); } })(this);
in json Whitespace (Space, Horizontal tab, Line feed or New line or Carriage return) outside of quotes
does not matter. Trailing commas are not allowed.
redux: to write a reducer, type
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
}
}
to create a function that you call on a class instead of on an instance, type
static funcName() {}
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/static
python: in requests.get() the difference between the data={} argument and the params={} argument is
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.
on mobile if I want an element to stick to the bottom
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
great css variables tutorial
https://www.youtube.com/watch?v=sQUB039MG0I
to make a space between grid columns, type
grid-gap:10px;
to be able to use a css variable with a number, type
–my-var: 20;
width: calc(var(20) * 1px);
to have css target a sibling, type
~
RN: To allow user to unfocus a TextInput by clicking outside the input,
Use a ScrollView as the wrapper div instead of a View
https://stackoverflow.com/questions/43431896/unfocus-a-textinput-in-react-native