Category Archives: Javascript

Miscellaneous React js notes

useEffect Notes

useEffect is called on initial load and every update after unless an empty dependency array is entered.. then it is only performed on first load:

 

For ajax calls on initial loads or in useEffect in general..async/await is only allowed if done in this way:

useEffect & setState

useEffect generally would get the “stale” state value however we can pass in a callback to the setState function in order to recieve/use the previous states value

 

The remaining problem with this is that you can only access the previous state value if you are setting (setSomeState) it. One work around that is provided is to use Refs

Using useRefs for current state value in useEffect

Refs exist outside of the re-render cycle and there for their actual current value isn’t effected by re-renders and so the value at ref.current will stay “current”. So the ref.current value will be what it was set last and not being reset or altered by a re-render. However, refs aren’t reactive.

The problem with this approach is that refs aren’t reactive and so shouldn’t be used like how <div>The count is: {count}</div> is displayed because the actual value that is displayed (the counting would still happen behind the scene tho ) won’t update until the component is re-rendered.

React Router

Import react-router-dom to use for web. Wrap <BrowserRouter></BroswerRouter> around <App/> in the index.js

To create routes you would do the following:

 

Link vs NavLink

To link to a route you can use Link or NavLink. The difference mostly is that Link will just create a <a> element pointing to the route ( which doesn’t actually issue a GET request like a link normally would ). Navlink will do the same thing but it is to be used in menus because you can set a prop in Navlink to indicate the “active” route so it can be styled properly.

 

Passing a prop to a route ( render vs component props )

 

URL Parameters with Router

When a route is declared and component/render/children is used, 3 things are passed to component/render/children under one component.. — history, location , match

So we can do the following to extract the parameter in a given route

 

Redirects

Can use Redirect component from react-router-dom .

 

Redirect programmatically 

This is done by pushing on the browser history stack. In order to be able to do that, the routeProps has to be passed down when the <Route/> is created. This is done automatically if using componenet={SomeComponent} but needs to be passed manually if done via render instead. i.e. You would only need to use render if you want to pass other props to the Route’s component.

 

Some differences of history.push vs <Redirect>

<Redirect /> won’t change the back button so if you redirect to a url that goes to a 404 then hitting the back button won’t bring them back to the url that will re-redirect to the 404 page. history.push will make the back button to the route that was pushed – so, if history.push to a route that goes to a 404 then hitting the back button will bring it back to the route that took it to the 404 and will be a endless loop.

Redirecting via history.push when the component has no route its self and so no routeProps – use withRouter

 

props.history.goBack() and props.history.goFoward()

These methods are available if needed to create functionality in the app similiar to the browsers forward and back button.

 

React Context API

Components can easier share values/functions by being wrapped in a Context.Provider component. Any component that uses that particular Context will be re-rendered when that Context’s value changes. This may cause un-wanted re-renders.

An example of using the Context Hook:

 

One issue with above is the todoContext using an object for the values ( values={{count:100}} ) , this will cause needless re-renders because the object will be rebuilt every time.

Setting Disabled attribute based on a function (computed property) that returns a boolean 

 

Conditionally show a component based on a state array not being empty.

Casting the input.Values.length as a Boolean enables this to be possible. Without casting , it would return a 0 to the screen which is not what is desired.

 

Setup Codesandbox.io + Jest to work with React Components for testing.

First step is create a new sandbox with the create-react-app base. Then add these three dependencies to your sandbox.

enzyme & enzyme-adapter-react-16 & @testing-library/react

The enzyme-adapter-react-16 name will slightly change with newer releases of react.

Next, create a file in your src folder and name it setupTests.js . This files goves jest with the ability to understand React.

Also, insert this in to your package.json file.

Now, for our test scenario we will create and use a functional component ( using hooks ) that has 1 input ( that will use useState ) and 1 prop to use and test.

 

Miscellaneous Javascript Notes

Common Regex:

For checking for a format such as : (856) 999-7777  use regex:   /^\(\d{3}\)\s\d{3}-\d{4}$/

Ternary

Boolean conversions

A number 0, an empty string ""nullundefined, and NaN all become false. Because of that they are called “falsy” values.

Break & Continue

 

For loop:

 

Breaking out of a nest for loop ( named loops ):

Curried Functions

The process of breaking up a multiple parameter function in to multiple single(or more) parameters.

Useful for : If you don’t provide all parameters for a function, it returns a function whose input are the remaining parameters and whose output is the result of the original function.

Useful ways of using Currying:

 

Closures

Closures provide two unique purposes. One is memory management and the other is encapsulation. Currying is an example usage of Closures.

Using closures creates a lexical scope that will store variables within it and are available for subsequent functions that may be returned within a function.

For Encapsulation the same idea exists except that a function that is declared within another function but not directly returned (instead as maybe a property of a returned object instead) will still benefit from being able to access the internal values of the nesting closure function

Closure to count how many times a function to ran

The function initializes a counter and then returns an anonymous function which increments the counter. To be used, a variable must be made that is equal to the containing function and is invoked. Then, the variable created will be invoked in order to increase the count.

Example below:

 

Hoisting

Variable that are defined are brought to the top of the file ( or function  it resides in i.e. IIFE ) but remain undefined until the line where the variable is set.

For example.

function declarations are also hoisted but are set at the time that the interrupter runs. function declarations can be safer for this reason.

When a variable or function is created within another function or IIFE, it is hoisted only to the top of the parent function (function scope) – not the global scope. This only applies when using var as it is function scoped.

const and let are aware of global/function scope but unlike var, const and let are aware of block scope (function,if,for,while loop). Hoisting with const and let only happens to the top of the block it was declared in.

unlike var, const and let do not have any value when hoisted until the actual declaration is reached and will throw an error if trying to be accessed before it’s declaration is reached. var is automatically undefined until it’s declaration is reached and will not throw an error if is tried to be accessed before it is defined/declared.

Strict mode

Enabled by placing ‘use strict’; at the top of a js file.

Strict mode will enforce a few things. One is that a variable must use either var,let or const or it will be considered undefined.

In strict mode, all function parameters must have an unique name. Otherwise, an error will be thrown.

Without strict mode, JavaScript will interpret the last use of the parameters name as the prevailing value.

Strict mode also prevents the ability to delete properties on objects that we shouldn’t be able to delete such as:

 

this and controlling it

this is the object that the function is a property of

Four ways to control this

  1. function constructors and the use of “new”
  2. implicit binding (most common)
  3. explicit binding ( i.e. use of bind(), call() and apply()  )
  4. arrow function to maintain lexical scope of this

 

Misc Notes

Objects i.e. {} can only have properties as string types.

If a property of an object is given another object.. Javascript will turn the object property in to a string of “[object object]”

 

call() and apply() methods

Both are available for any function that is created. call() is another way to call a function and to give it different variables. You can also change the “this” context.

apply() is very similar except that it uses an array [] to input the remaining parameters.

For example:

Copy by value vs reference

If a variable has a primitive type ( number, string, boolean ) and is copied by another variable.. it is copied by value. So if the original variable’s value is changed, the new variable that was made when coping the original will not be changed.

If a non-primitive type is copied – it is by reference. So if a variable is set to an array and another variable is set to that variable.. both will reference that array and if either variable pushes/pops a value out of the array.. both will reflect that same array.

One way to copy an array variable to another variable by value is to do the following:

Comparing two different identical objects (or arrays) will never result in true. One way to check however is to JSON.stringify both and than compare.

Array Constructor

 

 

JSON Notes

Double quotes have to be used , ” “, not single quotes.

All property names ( and on nested object properties ) are strings and so must be wrapped in double quotes. undefined and functions can not be used in JSON

Event Loop

The event loop is a event queue where callbacks are placed to be processed after the main thread of execution is done.

For Example:

3 Ways to Create an Object in Javascript

indexOf Method (String and Array)

Properly add & remove eventListeners

In order to remove an eventListener that was assigned, the handling function must be a named function variable and can not be just a anonymous function.

 

Copy objects and exclude selected properties

source: https://enmascript.com/articles/2019/09/20/two-exceptional-use-cases-for-the-spread-operator-you-may-not-know-of

Object Destructuring and aliasing

Destructuring is a way to extract an objects property upon assignment.

 

String Functions

indexOf(wordToLookFor) – will find the starting position of the wordToLookFor and return the starting index. If nothing is found it will return -1

localeCompare() − Returns a number indicating whether a reference string comes before or after or is the same as the given string in sort order

prototype vs __proto__

 

How to lazy load using jQuery

Check the comments in code for explanations. This example relies on jQuery.

 

Vuejs notes

Mass registering global components

Import top level components and export them as an Array:

Then in main.js we loop through the components and register them globally:

 

Useful Vuejs libraries

https://cdn.jsdelivr.net/npm/v-mask/dist/v-mask.min.js  can be used for phone and zip code masks to prevent bad input. Also works with Element UI. Just include via cdn and then can be used as a directive i.e. :