show line numbers in conde snippets

This commit is contained in:
Marcello 2023-10-20 18:22:46 +02:00
parent cd1df0e376
commit 255a68d673
82 changed files with 1249 additions and 1251 deletions

View file

@ -14,7 +14,7 @@ AJAX Interaction:
## XMLHttpRequest
```js
```js linenums="1"
var request = new XMLHttpRequest();
request.addEventListener(event, function() {...});
@ -39,7 +39,7 @@ To check the status use `XMLHttpRequest.status` and `XMLHttpRequest.statusText`.
**Alternative `XMLHttpRequest` using `onLoad`**:
```js
```js linenums="1"
var request = new XMLHttpRequest();
request.open('GET', 'myservice/username?id=some-unique-id');
request.onload = function(){
@ -54,7 +54,7 @@ request.send();
**Alternative `XMLHttpRequest` using `readyState`**:
```js
```js linenums="1"
var request = new XMLHttpRequest(), method ='GET', url ='https://developer.mozilla.org/';
request.open(method, url, true);
@ -77,7 +77,7 @@ request.send();
Old versions of IE don't implement XMLHttpRequest. You must use the ActiveXObject if XMLHttpRequest is not available
```js
```js linenums="1"
var request =window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
// OR

View file

@ -10,7 +10,7 @@ The document object is *globally available* in the browser. It allows to access
`getElementById()` and `querySelector()` return a single element.
`getElementsByClassName()`, `getElementsByTagName()`, and `querySelectorAll()` return a collection of elements.
```js
```js linenums="1"
Javascript
// By Id
var node = document.getElementById('id');
@ -32,7 +32,7 @@ var nodes = document.querySelectorAll('css-selector');
It's possible access and change the attributes of a DOM node using the *dot notation*.
```js
```js linenums="1"
// Changing the src of an image:
var image = document.getElementById('id');
var oldImageSource = image.src;
@ -48,7 +48,7 @@ node.className = 'new-class';
It's possible to access and change the styles of a DOM nodes via the **style** property.
CSS property names with a `-` must be **camelCased** and number properties must have a unit.
```css
```css linenums="1"
body {
color: red;
background-color: pink;
@ -56,7 +56,7 @@ body {
}
```
```js
```js linenums="1"
var pageNode = document.body;
pageNode.style.color = 'red';
pageNode.style.backgroundColor = 'pink';
@ -67,7 +67,7 @@ pageNode.style.paddingTop = '10px';
Each DOM node has an `innerHTML` attribute. It contains the HTML of all its children.
```js
```js linenums="1"
var pageNode = document.body;
console.log(pageNode.innerHTML);
@ -96,13 +96,13 @@ To change the actual text of a node, `textContent` may be a better choice:
In `page.html`:
```html
```html linenums="1"
<input type="" id="identifier" value="">
```
In `script.js`:
```js
```js linenums="1"
var formNode = document.getElementById("Identifier");
var value = formNode.value;
```
@ -111,7 +111,7 @@ var value = formNode.value;
The document object also allows to create new nodes from scratch.
```js
```js linenums="1"
// create node
document.createElement('tagName');
document.createTextNode('text');
@ -129,7 +129,7 @@ node.parentNode.removeChild(node);
Example:
```js
```js linenums="1"
var body = document.body;
var newImg = document.createElement('img');
@ -148,7 +148,7 @@ body.appendChild(newParagraph);
### Creating DOM Nodes with Constructor Functions
```js
```js linenums="1"
function Node(params) {
this.node = document.createElement("tag");

View file

@ -12,7 +12,7 @@ Event Types:
### Managing Event Listeners
```js
```js linenums="1"
var domNode = document.getElementById("id");
var onEvent = function(event) { // parameter contains info on the triggered event
@ -38,7 +38,7 @@ Event Options:
- `bubbles` (bool): whether the event propagates through bubbling
- `cancellable` (bool): if `true` the "default action" may be prevented
```js
```js linenums="1"
let event = new Event(type [,options]); // create the event, type can be custom
let event = new CustomEvent(type, { detail: /* custom data */ }); // create event w/ custom data
domNode.dispatchEvent(event); // launch the event
@ -53,7 +53,7 @@ The window object is the assumed global object on a page.
Animation in JavascriptThe standard way to animate in JS is to use window methods.
It's possible to animate CSS styles to change size, transparency, position, color, etc.
```js
```js linenums="1"
//Calls a function once after a delay
window.setTimeout(callbackFunction, delayMilliseconds);
@ -73,7 +73,7 @@ window.requestAnimationFrame(callbackFunction);
[StackOverflow](https://stackoverflow.com/a/294273/8319610)
[Wrong dimensions at runtime](https://stackoverflow.com/a/46772849/8319610)
```js
```js linenums="1"
> console.log(document.getElementById('id').getBoundingClientRect());
DOMRect {
bottom: 177,

View file

@ -1,4 +1,4 @@
# JavaScript
# JavaScript
## Basics
@ -11,14 +11,14 @@
### Comments
```javascript
```javascript linenums="1"
//single line comment
/*multiline comment*/
```
### File Header
```javascript
```javascript linenums="1"
/**
* @file filename.js
* @author author's name
@ -32,7 +32,7 @@
If located at the top of the script the whole script works the “modern” way (enables post-ES5 functionalities).
```js
```js linenums="1"
"use strict"
// script contents
@ -42,7 +42,7 @@ If located at the top of the script the whole script works the “modern” way
Interrupts script execution until closure, **to be avoided**
```javascript
```javascript linenums="1"
alert("message");
```
@ -69,7 +69,7 @@ Variable names can only contain numbers, digits, underscores and $. Variable nam
Variable declared with `let` are in local to the code block in which are declared.
Variable declared with `var` are local only if declared in a function.
```js
```js linenums="1"
function func(){
variable = value; // implicitly declared as a global variable
var variable = value; // local variable
@ -99,7 +99,7 @@ Hard-coded values are UPPERCASE and snake_case, camelCase otherwise.
Only numeric type is `number`.
```javascript
```javascript linenums="1"
let number = 10; //integer numbers
number = 15.7; //floating point numbers
number = Infinity; //mathematical infinity
@ -115,7 +115,7 @@ Mathematical expression will *never* cause an error. At worst the result will be
### String data type
```javascript
```javascript linenums="1"
let string = "text";
let string$ = 'text';
let string_ = `text ${expression}`; //string interpolation (needs backticks)
@ -137,7 +137,7 @@ Property access is unpredictable:
If the parameters to slice are negative, they reference the string from the end. Substring and substr doesn´t.
```js
```js linenums="1"
string.slice(begin [, end]);
string.substring(from [, to]);
string.substr(start [, length]);
@ -145,27 +145,27 @@ string.substr(start [, length]);
### Boolean data type
```javascript
```javascript linenums="1"
let boolean = true;
let boolean_ = false;
```
### Null data type
```javascript
```javascript linenums="1"
let _ = null;
```
### Undefined
```javascript
```javascript linenums="1"
let $; //value is "undefined"
$ = undefined;
```
### Typeof()
```javascript
```javascript linenums="1"
typeof x; //returns the type of the variable x as a string
typeof(x); //returns the type of the variable x as a string
```
@ -176,7 +176,7 @@ It is a special value with a separate type of its own. So, again, this is an err
### Type Casting
```javascript
```javascript linenums="1"
String(value); //converts value to string
Number(value); //converts value to a number
@ -200,7 +200,7 @@ typeof var_ == "number"; // typeof returns a string with the name of the type
### Type Checking
```js
```js linenums="1"
isNaN(var); // converts var in number and then check if is NaN
Number("A") == NaN; //false ?!?
@ -209,7 +209,7 @@ Number("A") == NaN; //false ?!?
### Dangerous & Stupid Implicit Type Casting
```js
```js linenums="1"
2 + 'text'; //"2text", implicit conversion and concatenation
1 + "1"; //"11", implicit conversion and concatenation
"1" + 1; //"11", implicit conversion and concatenation
@ -305,7 +305,7 @@ Number("A") == NaN; //false ?!?
### IF-ELSE
```javascript
```javascript linenums="1"
if (condition) {
//code here
} else {
@ -315,7 +315,7 @@ if (condition) {
### IF-ELSE Multi-Branch
```javascript
```javascript linenums="1"
if (condition) {
//code here
} else if (condition) {
@ -331,7 +331,7 @@ if (condition) {
### Switch Statement
```javascript
```javascript linenums="1"
switch (expression) {
case expression:
//code here
@ -347,7 +347,7 @@ switch (expression) {
### While Loop
```javascript
```javascript linenums="1"
while (condition) {
//code here
}
@ -355,7 +355,7 @@ while (condition) {
### Do-While Loop
```javascript
```javascript linenums="1"
do {
//code here
} while (condition);
@ -363,7 +363,7 @@ do {
### For Loop
```javascript
```javascript linenums="1"
// basic for
for (begin; condition; step) { }
@ -384,7 +384,7 @@ iterable.forEach(() => { /* statements */ });
`break;` exits the loop.
`continue;` skip to next loop cycle.
```javascript
```javascript linenums="1"
label: for(begin; condition; step) {
//code here
}
@ -394,7 +394,7 @@ break label; //breaks labelled loop and nested loops inside it
## Arrays
```js
```js linenums="1"
let array = []; // empty array
let array = ["text", 3.14, [1.41]]; // array declaration and initialization
@ -417,7 +417,7 @@ array.splice(start, deleteCount, [items_to_add]); // remove and RETURN items fr
### `filter()` & `map()`, `reduce()`
```js
```js linenums="1"
let array = [ items ];
// execute an operation on each item, producing a new array
@ -432,7 +432,7 @@ array.reduce((x, y) => ...);
## Spread Operator (...)
```js
```js linenums="1"
// arrays
let array1 = [ 1, 2, 3, 4, 5, 6 ];
let array2 = [ 7, 8, 9, 10 ];
@ -457,7 +457,7 @@ func(arg0, ...args);
## Dictionaries
```js
```js linenums="1"
let dict = { FirstName: "Chris", "one": 1, 1: "some value" };
@ -471,7 +471,7 @@ dict.FirstName = "Chris";
### Iterating Key-Value pairs
```js
```js linenums="1"
for(let key in dict) {
let value = dict[key];
@ -485,7 +485,7 @@ Object.keys(dict).forEach(key => { });
### JSDOC documentation standard
```javascript
```javascript linenums="1"
/**
* @param {type} parameter - description
* @returns {type} parameter - description
@ -494,7 +494,7 @@ Object.keys(dict).forEach(key => { });
### Function Declaration
```javascript
```javascript linenums="1"
// ...args will contain extra parameters (rest argument)
function functionName(parameter=default-value, ...args) {
//code here
@ -504,7 +504,7 @@ function functionName(parameter=default-value, ...args) {
### Default Parameters (old versions)
```javascript
```javascript linenums="1"
function functionName(parameters) {
if (parameter == undefined) {
parameter = value;
@ -517,7 +517,7 @@ function functionName(parameters) {
### Function Expressions
```javascript
```javascript linenums="1"
let functionName = function(parameters) {
//code here
return expression;
@ -526,7 +526,7 @@ let functionName = function(parameters) {
### Arrow Functions
```javascript
```javascript linenums="1"
(input) => { /* statements */ }
(input) => expression;
input => expression; // parenthesis are optional
@ -552,7 +552,7 @@ An object is a collection of related data and/or functionality.
**Note**: It's not possible to transform a variable in an object simply by using the object assignment.
```js
```js linenums="1"
let variable = value;
// object literal
@ -596,7 +596,7 @@ Object.entries(obj); // list contents as key-value pairs
JavaScript uses special functions called **constructor functions** to define and initialize objects and their features.
Notice that it has all the features you'd expect in a function, although it doesn't return anything or explicitly create an object — it basically just defines properties and methods.
```js
```js linenums="1"
// constructor function definition
function Class(params) {
this.property = param;
@ -622,7 +622,7 @@ An object's prototype object may also have a prototype object, which it inherits
This is often referred to as a **prototype chain**, and explains why different objects have properties and methods defined on other objects available to them.
If a method is implemented on an object (and not it's prototype) then only that object will heve that method and not all the ones that come from the same prototype.
```js
```js linenums="1"
// constructor function
function Obj(param1, ...) {
this.param1 = param1,
@ -640,7 +640,7 @@ obj.method(); // call method from prototype
### Extending with prototypes
```js
```js linenums="1"
// constructor function
function DerivedObj(param1, param2, ...) {
Obj.call(this, param1); // use prototype constructor
@ -661,7 +661,7 @@ dobj.method(); // call method from prototype
### Classes (ES6+)
```js
```js linenums="1"
class Obj {
constructor(param1, ...) {
this.param1 = param1,
@ -686,7 +686,7 @@ obj.func(); // call method
### Extending with Classes
```js
```js linenums="1"
class DerivedObj extends Obj {
constructor(param1, param2, ...){
super(param1); // use superclass constructor
@ -704,7 +704,7 @@ dobj.newFunc();
### Object deconstruction
```js
```js linenums="1"
let obj = {
property: value,
...
@ -717,14 +717,14 @@ let { property: var1, var2 = default_value } = obj; // use default values if ob
### Array Deconstruction
```js
```js linenums="1"
let array = [ 1, 2, 3, 4, 5, 6 ];
let [first, , third, , seventh = "missing" ] = array; // extract specific values from array
```
## Serialization
```js
```js linenums="1"
let object = {
// object attributes
}
@ -741,7 +741,7 @@ let object = JSON.parse(json); // deserialize to Object
Function runs *once* after an interval of time.
```js
```js linenums="1"
// param1, param2, ... are the arguments passed to the function (IE9+)
let timerId = setTimeout(func [, milliseconds, param1, param2, ... ]); // wait milliseconds before executing the code (params are read at execution time)
@ -776,7 +776,7 @@ useTimeout();
### `let` vs `var` with `setTimeout`
```js
```js linenums="1"
// let instantiates a new variable for each iteration
for (let i = 0; i < 3; ++i) {
setTimeout(function() {
@ -795,7 +795,7 @@ for (var i = 0; i < 3; ++i) {
### Preserving the context
```js
```js linenums="1"
let obj = {
prop: value,
@ -824,7 +824,7 @@ let obj = {
Function runs regularly with a specified interval. JavaScript is **Single Threaded**.
```js
```js linenums="1"
// param1, param2, ... are the arguments passed to the function (IE9+)
let timerId = setInterval(func, milliseconds [, param1, param2, ... ]); // (params are read at execution time)
@ -852,7 +852,7 @@ There are generally 4 types of JavaScript date input formats:
- Long Date: `"Mar 25 2015"` or `"25 Mar 2015"`
- Full Date: `"Wednesday March 25 2015"`
```js
```js linenums="1"
// constructors
new Date();
new Date(milliseconds);
@ -892,7 +892,7 @@ let date = new Date(msec);
Comparison operators work also on dates
```js
```js linenums="1"
let date1 = new Date();
let date2 = new Date("May 24, 2017 10:50:00");
@ -909,20 +909,20 @@ if(date1 > date2){
> **Note**: Firefox 68 and later define the origin of a page opened using a `file:///` URI as unique. Therefore, other resources in the same directory or its subdirectories no longer satisfy the CORS same-origin rule. This new behavior is enabled by default using the `privacy.file_unique_origin` preference.
```json
```json linenums="1"
"privacy.file_unique_origin": "false"
```
In `page.html`
```html
```html linenums="1"
<script src="scripts/module.js"></script>
<script src="scripts/script.js"></script>
```
In `module.js`:
```js
```js linenums="1"
// exporting individual fractures
export default function() {} // one per module
export func = () => expression; // zero or more per module
@ -942,7 +942,7 @@ export { func } from "other_script.js"
In `script.js`:
```js
```js linenums="1"
import default_func_alias, { func as alias } from "./module.js"; // import default and set alias
import { default as default_func_alias, func as alias } from "./module.js"; // import default and set alias
@ -951,7 +951,7 @@ default_func_alias();
alias();
```
```js
```js linenums="1"
import * from "./module.js"; // import all
module.function(); // use imported content with fully qualified name

View file

@ -4,7 +4,7 @@
### Download and link the file
```html
```html linenums="1"
<head>
<script src="jquery-x.x.x.min.js"></script>
</head>
@ -12,7 +12,7 @@
### Use a CDN
```html
```html linenums="1"
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/x.x.x/jquery.min.js"></script>
</head>
@ -34,7 +34,7 @@ CDNs serve a large fraction of the Internet content today, including web objects
### [Finding DOM elements](https://api.jquery.com/category/selectors/)
```js
```js linenums="1"
$('tag');
$("#id");
$(".class");
@ -42,11 +42,11 @@ $(".class");
### Manipulating DOM elements
```js
```js linenums="1"
$("p").addClass("special");
```
```html
```html linenums="1"
<!-- before -->
<p>Welcome to jQuery<p>
@ -56,11 +56,11 @@ $("p").addClass("special");
### Reading Elements
```html
```html linenums="1"
<a id="yahoo" href="http://www.yahoo.com" style="font-size:20px;">Yahoo!</a>
```
```js
```js linenums="1"
// find it & store it
var link = $('a#yahoo');
@ -72,14 +72,14 @@ link.css('font-size'); // '20px
### Modifying Elements
```js
```js linenums="1"
// jQuery
$('a').html('Yahoo!');
$('a').attr('href', 'http://www.yahoo.com');
$('a').css({'color': 'purple'});
```
```html
```html linenums="1"
<!-- before -->
<a href="http://www.google.com">Google</a>
@ -89,7 +89,7 @@ $('a').css({'color': 'purple'});
### Create, Store, Manipulate and inject
```js
```js linenums="1"
let paragraph = $('<p class="intro">Welcome<p>'); // create and store element
paragraph.css('property', 'value'); // manipulate element
@ -99,7 +99,7 @@ $("body").append(paragraph); // inject in DOM
### Regular DOM Nodes to jQuery Objects
```js
```js linenums="1"
var paragraphs = $('p'); // an array
var aParagraph = paragraphs[0]; // a regular DOM node
var $aParagraph = $(paragraphs[0]); // a jQuery Object
@ -114,7 +114,7 @@ for(var i = 0; i < paragraphs.length; i++) {
## [Events](https://api.jquery.com/category/events/)
```js
```js linenums="1"
var onButtonClick = function() {
console.log('clicked!');
}
@ -133,7 +133,7 @@ $('button').click(onButtonClick);
### Preventing Default Event
```js
```js linenums="1"
$('selector').on('event', function(event) {
event.preventDefault();
// custom logic
@ -144,13 +144,13 @@ $('selector').on('event', function(event) {
In the HTML, add a `<script>` ag that hotlinks to the CDN or source file:
```html
```html linenums="1"
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.min.js"><script>
```
In the JavaScript call the jQuery plugin on the DOM:
```js
```js linenums="1"
$("form").validate();
```
@ -160,7 +160,7 @@ $("form").validate();
### Patters & Anti-Patterns
```js
```js linenums="1"
// Pattern: name variables with $var
$myVar =$('#myNode');
@ -179,7 +179,7 @@ $(document).on('click', 'p', function(argument){
### Chaining
```js
```js linenums="1"
banner.css('color', 'red');
banner.html('Welcome!');
banner.show();
@ -197,7 +197,7 @@ banner.css('color', 'red')
DOM manipulation and event binding doesn't work if the `<script>` is in the `<head>`
```js
```js linenums="1"
$(document).ready(function() {
// the DOM is fully loaded
});
@ -209,7 +209,7 @@ $(window).on('load', function(){
## AJAX (jQuery `1.5`+)
```js
```js linenums="1"
$.ajax({
method: 'POST',
url: 'some.php',

View file

@ -16,7 +16,7 @@ Router Types:
- *BrowserRouter*: `/route`, uses HTML5 history API to provide clean URLs
- *MemoryRouter*: no URL
```js
```js linenums="1"
// index.js
//other imports ...
@ -31,7 +31,7 @@ React.render(
)
```
```js
```js linenums="1"
// Component.js
import { Route, Route } from "react-router-dom";
@ -52,7 +52,7 @@ import { Route, Route } from "react-router-dom";
### URL Parameters & Query String
```js
```js linenums="1"
// Given
<Route path="/route/:placeholder" element={<Component props={props} />} />
// URL: app.com/route/sub-route?param=value
@ -66,7 +66,7 @@ function Component(props) {
### Redirecting
```js
```js linenums="1"
import { Navigate } from "react-router-dom";
// redirects to another URL on render, shouldn't be rendered on component mount but after an action
@ -80,7 +80,7 @@ props.history.push("/new-route");
### Prompts
```js
```js linenums="1"
import { Prompt } from "react-router-dom";
// displays a prompt when the condition is true
@ -91,7 +91,7 @@ import { Prompt } from "react-router-dom";
Clicks on a link created with React-Router will be captured by react an all the routing will happen client side.
```js
```js linenums="1"
import { Link } from "react-router-dom";
// TARGET: <Route path="/route/:itemId" />

View file

@ -4,7 +4,7 @@
### Jest Configuration
```js
```js linenums="1"
// jest.config.js
module.exports = {
testEnvironment: 'jsdom',
@ -18,7 +18,7 @@ module.exports = {
[Expect docs](https://jestjs.io/docs/expect)
```js
```js linenums="1"
// .spec.js or .test.js
it("test description", () => {
// test body
@ -36,7 +36,7 @@ describe("test group name", () => {
In `Component.Snapshots.js`:
```js
```js linenums="1"
import React from "react";
import renderer from "react-test-renderer";
@ -60,7 +60,7 @@ it("test description", () => {
### Enzyme Configuration
```js
```js linenums="1"
// testSetup.js
import { configure } from "enzyme";
import Adapter from "enzyme-adapter-react-<version>";
@ -72,7 +72,7 @@ configure({ adapter: new Adapter() });
In `Component.test.js`:
```js
```js linenums="1"
import React from "react";
import { shallow, mount } from "enzyme";
// eventual wrapper components (react-router, react-redux's provider, ...) for mount render
@ -125,7 +125,7 @@ Encourages to write test based on what the user sees. So components are always *
In `Components.test.js`:
```js
```js linenums="1"
import React from "react";
import { cleanup, render } from "@testing-library/react";

View file

@ -9,7 +9,7 @@ There are two types of react components:
Both types can be stateful and have side effects or be purely presentational.
```jsx
```jsx linenums="1"
// functional component
const Component = (props) => {
return (
@ -33,7 +33,7 @@ Within the component state can be changed while the props object represent fixed
JSX syntax can represent HTML but gets converted to pure JavaScript before being sent to the browser:
```js
```js linenums="1"
// JSX
const element = (
<h1 className="greeting">Hello, world!</h1>
@ -49,7 +49,7 @@ const element = React.createElement(
### App Entry-point
```js
```js linenums="1"
const container = document.getElementById('root')!;
const root = createRoot(container);
@ -59,7 +59,7 @@ root.render(element)
### Dynamic Expressions
```js
```js linenums="1"
<tag>{expression}</tag> // expression is evaluated an it's result is displayed
<tag onEvent={funcReference}>{expression}</tag>
<tag onEvent={() => func(args)}>{expression}</tag>
@ -67,7 +67,7 @@ root.render(element)
### Props
```js
```js linenums="1"
<Component propName={value} /> // pass a value the component
<Component propName={funcReference} /> // pass a function to the component
@ -83,7 +83,7 @@ class Component extends React.Component{
### Simple Function Component
```js
```js linenums="1"
// Button.js
import { useState } from "react";
@ -105,7 +105,7 @@ export default Button;
### Simple Class Component
```js
```js linenums="1"
class Button extends React.Component {
state = {count: 0};
@ -137,7 +137,7 @@ class Button extends React.Component {
### Nesting Components
```js
```js linenums="1"
import { useState } from "react";
function Button(props) {
@ -173,7 +173,7 @@ export default App;
### User Input (Forms)
```js
```js linenums="1"
function Form() {
const [userName, setUserName] = useState("");
@ -198,7 +198,7 @@ function Form() {
### Lists of Components
```js
```js linenums="1"
// ...
<div>
{array.map(item => <Component key={uniqueID}>)}
@ -219,7 +219,7 @@ Hook used to create a state object.
- state object (getter)
- updater function (setter)
```js
```js linenums="1"
const [state, setState] = useState(default);
```
@ -227,7 +227,7 @@ const [state, setState] = useState(default);
Hook used to trigger an action on each render of the component or when one of the watched items changes.
```js
```js linenums="1"
useEffect(() => {
// "side effects" operations
@ -238,7 +238,7 @@ useEffect(() => {
### Custom Hooks
```js
```js linenums="1"
// hook definitions
const useCustomHook = () => {
// eventual state definitions

View file

@ -9,7 +9,7 @@ Connected components are wrapped in a call to `connect`. Way of solving the prob
In `Component.js`:
```js
```js linenums="1"
export function Component(props) { /* ... */ } // export unconnected component
export default connect(mapStateToProps, mapDispatchToProps)(Component) // default export of connected component
@ -17,7 +17,7 @@ export default connect(mapStateToProps, mapDispatchToProps)(Component) // defau
In `Component.test.js`:
```js
```js linenums="1"
import React from "react";
// import enzyme or react testing library
@ -48,7 +48,7 @@ it("test description", () => {
## Tests for Action Creators
```js
```js linenums="1"
import * as actions from "path/to/actionCreators";
// import eventual action types constants
// import mock data
@ -65,7 +65,7 @@ it("test description", () => {
## Tests for Reducers
```js
```js linenums="1"
import reducer from "path/to/reducer";
import * as actions from "path/to/actionCreators";
@ -83,7 +83,7 @@ it("test description", () => {
## Tests for the Store
```js
```js linenums="1"
import { createStore } from "redux";
import rootReducer from "path/to/rootReducer";
@ -111,7 +111,7 @@ Thunk testing requires the mocking of:
- store (using `redux-mock-store`)
- HTTP calls (using `fetch-mock`)
```js
```js linenums="1"
import thunk from "redux-thunk";
import fetchMock from "fetch-mock";
import configureMockStore from "redux-mock-store";

View file

@ -11,7 +11,7 @@ By convention, that information is stored in a field called `payload`.
**Action Creators** are functions that create and return action objects.
```js
```js linenums="1"
function actionCreator(data)
{
return { type: ACTION_TYPE, payload: data }; // action obj
@ -30,7 +30,7 @@ The store will run its reducer function and save the new state value inside.
In `initialState.js`;
```js
```js linenums="1"
export default {
// initial state here
}
@ -38,7 +38,7 @@ export default {
In `configStore.js`:
```js
```js linenums="1"
// configStore.js
import { createStore, applyMiddleware, compose } from "redux";
@ -71,7 +71,7 @@ Reducers must **always** follow some specific rules:
Instead, they must make *immutable updates*, by copying the existing `state` and making changes to the copied values.
- They must not do any asynchronous logic, calculate random values, or cause other "side effects"
```js
```js linenums="1"
import initialState from "path/to/initialState";
function reducer(state = initialState, action) {
@ -118,7 +118,7 @@ Presentational Components:
Used at the root component and wraps all the application.
```js
```js linenums="1"
// index.js
import React from 'react';
import ReactDOM from 'react-dom';
@ -139,7 +139,7 @@ ReactDOM.render(
);
```
```js
```js linenums="1"
// Component.js
import { connect } from 'react-redux';
import { increment, decrement, reset } from './actionCreators';
@ -183,7 +183,7 @@ A "thunk" is a function that wraps an expression to delay it's evaluation.
In `configStore.js`:
```js
```js linenums="1"
import { createStore, applyMiddleware, compose } from "redux";
import thunk from "redux-thunk";
@ -199,7 +199,7 @@ function configStore(initialState) {
}
```
```js
```js linenums="1"
// usually action on async func success
function actionCreator(arg) {
return { type: TYPE, data: arg };
@ -241,7 +241,7 @@ Using Create React App
The recommended way to start new apps with React and Redux is by using the official Redux+JS template or Redux+TS template for Create React App, which takes advantage of Redux Toolkit and React Redux's integration with React components.
```sh
```sh linenums="1"
# Redux + Plain JS template
npx create-react-app my-app --template redux
@ -286,7 +286,7 @@ Included Default Middleware:
Currently, the return value of `getDefaultMiddleware()` is:
```js
```js linenums="1"
// development
const middleware = [thunk, immutableStateInvariant, serializableStateInvariant]
@ -294,7 +294,7 @@ const middleware = [thunk, immutableStateInvariant, serializableStateInvariant]
const middleware = [thunk]
```
```js
```js linenums="1"
import { combineReducers } from 'redux'
import { configureStore } from '@reduxjs/toolkit'
@ -320,7 +320,7 @@ export default store
### [`createAction`](https://redux-toolkit.js.org/api/createAction)
```js
```js linenums="1"
import { createAction } from '@reduxjs/toolkit';
const increment = createAction<number | undefined>('counter/increment');
@ -333,7 +333,7 @@ increment.toString(); // 'counter/increment'
### [`createReducer`](https://redux-toolkit.js.org/api/createReducer)
```js
```js linenums="1"
import { createAction, createReducer } from '@reduxjs/toolkit'
interface CounterState {
@ -368,7 +368,7 @@ Internally, it uses `createAction` and `createReducer`, so it's possible to use
**Note**: action types will have the `<slice-name>/<reducer-name>` shape.
```js
```js linenums="1"
import { createSlice, PayloadAction } from '@reduxjs/toolkit'
interface CounterState {
@ -415,7 +415,7 @@ The `payloadCreator` function will be called with two arguments:
The logic in the `payloadCreator` function may use any of these values as needed to calculate the result.
```js
```js linenums="1"
import { createAsyncThunk, createSlice } from '@reduxjs/toolkit'
const payloadCreator = async (arg, ThunkAPI): Promise<T> => { /* ... */ };
@ -444,7 +444,7 @@ It is intended to simplify common cases for loading data in a web application, e
RTK Query is included within the installation of the core Redux Toolkit package. It is available via either of the two entry points below:
```cs
```cs linenums="1"
import { createApi } from '@reduxjs/toolkit/query'
/* React-specific entry point that automatically generates hooks corresponding to the defined endpoints */

View file

@ -1,6 +1,6 @@
# [Svelte](https://svelte.dev/docs)
```sh
```sh linenums="1"
npx degit sveltejs/template <project name>
# set project to use typescript
@ -12,7 +12,7 @@ npm init vite@latest
## App Entry-point
```js
```js linenums="1"
import App from "./App.svelte"; // import the component
const app = new App({
@ -29,7 +29,7 @@ export default app;
### Basic Structure
```html
```html linenums="1"
<!-- code for the component -->
<script lang="ts">
import { Component } from "Component.svelte";
@ -57,7 +57,7 @@ export default app;
### If-Else
```js
```js linenums="1"
{#if <condition>}
// markup here
{:else if <condition>}
@ -69,7 +69,7 @@ export default app;
### Loops
```js
```js linenums="1"
{#each array as item, index} // index is optional
// markup here
{/each}
@ -81,7 +81,7 @@ export default app;
### Await Blocks
```js
```js linenums="1"
{#await promise}
<p>...waiting</p>
{:then number}
@ -103,7 +103,7 @@ The full list of modifiers:
- `once` — remove the handler after the first time it runs
- `self` — only trigger handler if `event.target` is the element itself
```js
```js linenums="1"
<script>
const eventHandler = () => {};
</script>
@ -119,7 +119,7 @@ The full list of modifiers:
## Binding
```html
```html linenums="1"
<script>
let name = "Foo";
</script>
@ -137,7 +137,7 @@ Often, some parts of a component's state need to be computed from other parts an
For these, Svelte has reactive declarations. They look like this:
```js
```js linenums="1"
let count = 0;
$: double = count * 2; // recalculated when count changes
// or
@ -149,7 +149,7 @@ $: <expression>
[Svelte Routing](https://github.com/EmilTholin/svelte-routing)
```js
```js linenums="1"
<!-- App.svelte -->
<script>
import { Router, Link, Route } from "svelte-routing";
@ -177,14 +177,14 @@ $: <expression>
## Data Stores
```js
```js linenums="1"
// stores.js
import { writable } from "svelte/store";
export const count = writable(0);
```
```html
```html linenums="1"
<script>
import { onDestroy } from "svelte";
import { count } from ".path/to/stores.js";