00 FE & ReactJS & Web Component Design & CSS & Websites & PHP - lukes8/wiki-notes GitHub Wiki
How to optimaze imports in VS code by saving file
You can also enable Organize Imports to run automatically when you save the file:
Open your settings (Ctrl + , or Cmd + ,).
Search for editor.codeActionsOnSave and place new row
"editor.codeActionsOnSave": {
"source.organizeImports": true //new row
}
Great tools, icons, images, resources by Jonas, animations
Free symbols for bullet points, emoticons, icons, just copy paste
https://www.i2symbol.com/facebook-emoticons
Waves effect
https://getwaves.io/
https://codingheroes.io/resources/
Send email from your code (good css design)
https://www.emailjs.com/
Images
https://unsplash.com/photos/KJzjIY_3lEY
Colors and variants with naming
https://www.eggradients.com/shades-of-green-color
Fonts, icons (needs to create custom kitset)
https://fontawesome.com/icons/dove?f=classic&s=solid
Icons fb, linked in etc.
www.ionic.io
E-commerce, e-shop, inspiration icons, layout (this is not advertising!)
https://www.econea.cz/
drmax.cz
www.klorane.com/
https://jobs.tieto.cz/cs/volne-pozice/ -----> puzzle style for cards, buttons, menu
https://superkvasaci.cz/
https://makejvit.cz/#hodnoty
https://www.cocuma.cz/jobs/ --> good card layout
You need to check both $mysqli and $statement. If they are false, you need to output $mysqli->error or $statement->error respectively.
#Simple example
$mysqli = new mysqli('localhost', 'buzUser', 'buzPassword');
$q = "UPDATE foo SET bar=1";
($statement = $mysqli->prepare($q)) or trigger_error($mysqli->error, E_USER_ERROR);
$statement->execute() or trigger_error($statement->error, E_USER_ERROR);
#Another good example with wrapper class for mysqli
# This is part of an application
class FuzDatabaseException extends Exception {
}
class Foo {
public $mysqli;
public function __construct(mysqli $mysqli) {
$this->mysqli = $mysqli;
}
public function updateBar() {
$q = "UPDATE foo SET bar=1";
$statement = $this->mysqli->prepare($q);
if (!$statement) {
throw new FuzDatabaseException($mysqli->error);
}
if (!$statement->execute()) {
throw new FuzDatabaseException($statement->error);
}
}
}
$foo = new Foo(new mysqli('localhost','buzUser','buzPassword'));
try {
$foo->updateBar();
} catch (FuzDatabaseException $e)
$msg = $e->getMessage();
// Now send warning emails, write log
}
Exceptions in PHP, array into string over implode, bind variables into stmt
Binding variables into query stmt
~~~~~~~~~~~
// prepare and bind
$stmt = $conn->prepare("INSERT INTO b4sonic (first_name) VALUES (?)");
$stmt->bind_param("s", $firstname);
// set parameters and execute
$stmt->execute();
Another solution
~~~~
$stmt = $mysqli->prepare("INSERT INTO CountryLanguage VALUES (?, ?, ?, ?)");
$stmt->bind_param('sssd', $code, $language, $official, $percent);
Tip:
It depends mainly on version of PHP server as every server has some of its limitations
Another solution since version 5.6 PHP
~~~~
Since PHP 5.6, you don't have to mess around with call_user_func_array() anymore.
Instead of:
$stmt->bind_param($param_types, $my_params_array);
you can just use the [splat operator](https://lornajane.net/posts/2014/php-5-6-and-the-splat-operator), like this:
$stmt->bind_param($param_types, ...$my_params_array); // exact code
Array into string
~~~~~~~~~
implode("delimiter ",$arr);
Exceptions
~~~~~~~~~
Simple way how to trigger some exception error. This is some kind of logging that we can use
($stmt = $this->db->prepare($sql)) or trigger_error($this->db->error, E_USER_ERROR);;
The key word here is trigger_error()
db->error is other saying mysqli->error, but db is just instance of mysqli nothing more (via PDO object)
Example how we can handle error via throwing exception and handling it via try catch block
public function processRequest(string $method, ?string $id): void
{
try {
$this->processResourceRequest($method, $id);
} catch (Exception | ErrorException $e) {
/* if something fails inside try block will be catched here */
error_log('Exception message: ' . $e->getMessage());
echo json_encode([
"errorMessage" => 'General error (see logs for more info)',
// "errorCode" => 500,
"id" => $id,
"errorMessageDetails" => $e->getMessage(),
"errorCodeLine" => $e->getLine(),
"errorCode" => $e->getCode(),
"errorFile" => $e->getFile(),
]);
return;
}
}
Method processResourceRequest():
We can have this block of code to throw Exception
$message = "green " . $sql . implode(" ", $params) . "# " . $types;
$severity = 1;
$filename = "file";
$lineno = 104;
if (true) {
throw new ErrorException($message, 0, $severity, $filename, $lineno);
}
or we can use just this simple method
trigger_error("some error green text");;
Shortcuts Visual studio Code
To remove unused imports
shift + alt + O
To display list of methods/fields (no matter if reactjs or php)
CTRL + SHIFT + O
To remove line
CTRL + SHIFT + K
To duplicate line
SHIFT + ALT + arrow
To move line up or down press
ALT + arrow
Bookmarks
ctrl + alt + k ..... put bookmark on specific line
ctrl + alt + j/l ..... toggle next occurence
alt + shift + o ..... remove unused imports
To clear all recently opened files from history
Press Ctrl + Shift + P
Then, within the Quick Open bar, type in >Clear Recently Opened
or you can just remove it after you press CTRL + E. There is an icon for deletion
Auth, php, hashing, bcrypt, base64, salt, session, btoa function to encrypt via base64
When Basic is used for the Authorization header, the authentication information is username:password in [Base64](https://en.wikipedia.org/wiki/Base64) encoding.
PHP only sets the PHP_AUTH_USER and PHP_AUTH_PW fields from the Authorization field. The HTTP_X_USERNAME and HTTP_X_PASSWORD fields relate to the X-Username and X-Password headers (not) sent by the client, ie. PHP sets them if it gets them with the request.
simple auth basic reactJS
https://jasonwatmore.com/post/2018/09/11/react-basic-http-authentication-tutorial-example
bcrypt
https://medium.com/boca-code/how-to-encrypt-password-in-your-react-app-before-you-send-it-to-the-api-6e10a06f0a8e
https://stackoverflow.com/questions/18084595/how-to-decrypt-hash-stored-by-bcrypt
https://www.geeksforgeeks.org/how-to-secure-hash-and-salt-for-php-passwords/
https://codereview.stackexchange.com/questions/40073/php-authentication-security
await fetch("/charge/pay", headers).then((response) => {
if (response.status >= 400 && response.status < 600) {
throw new Error("Bad response from server");
}
return response;
}).then((returnedResponse) => {
// Your response to manipulate
this.setState({
complete: true
});
}).catch((error) => {
// Your error is here!
console.log(error)
});
Null in php, concatenate strings
$b = null;
echo "b is " . is_null($b) . "<br>";
With '.' we can join the strings
$a = 'Hello';
// now $a contains "HelloWorld!"
$a .= " World!";
Arrays in php
Arrays have keys and values as below
<?php
$array = array(
"foo" => "bar",
"bar" => "foo",
);
// Using the short array syntax
$array = [
"foo" => "bar",
"bar" => "foo",
];
?>
<?php
$array = array(
1 => "a",
"1" => "b",
1.5 => "c",
true => "d",
);
var_dump($array);
?>
In this case the output will be.
As all the keys in the above example are cast to 1, the value will be overwritten on every new element and the last assigned value "d" is the only one left over.
array(1) {
[1]=>
string(1) "d"
}
Another example
<?php
$array = array(
"a",
"b",
6 => "c",
"d",
);
var_dump($array);
?>
In this case the output would be like this as key are generated with indexes automatically
array(4) {
[0]=>
string(1) "a"
[1]=>
string(1) "b"
[6]=>
string(1) "c"
[7]=>
string(1) "d"
}
We can have also array with different kind of object types
<?php
$array = array(
"foo" => "bar",
"bar" => "foo",
100 => -100,
-100 => 100,
);
var_dump($array);
?>
For this case the output would be
array(4) {
["foo"]=>
string(3) "bar"
["bar"]=>
string(3) "foo"
[100]=>
int(-100)
[-100]=>
int(100)
}
How to enumare through json object
const pageable = {
sort: "true",
sortProperty: sortProperty,
sortDirection: sortDirection,
numberOfElements: 1,
size: 10,
totalPages: 10,
page: 1,
};
var url_suffix = URL + '?';
for (var key in pageable) {
if (pageable.hasOwnProperty(key)) {
url_suffix += key + '=' + pageable[key] + '&';
}
}
console.log(url_suffix.slice(0, -1));
Result
http://localhost/your-php-server/items/?sort=true&sortProperty=id&sortDirection=asc&numberOfElements=1&size=10&totalPages=10&page=1
How to get path variables from php server http request
In this case we received request with GET method and get data via _GET global object
We can have this url with path variables
http://localhost/your-php-server/items/?sort=true&sortProperty=id&sortDirection=asc&numberOfElements=1&size=10&totalPages=10&page=1
switch ($method) {
case "GET":
$data = [
"sort" => $_GET['sort'] ?? '',
'sortProperty' => $_GET['sortProperty'] ?? '',
'sortDirection' => $_GET['sortDirection'] ?? '',
'numberOfElements' => $_GET['numberOfElements'] ?? '',
'size' => $_GET['size'] ?? '',
'totalPages' => $_GET['totalPages'] ?? '',
'page' => $_GET['page'] ?? '',
];
error_log(sizeof($data));
error_log($data['sort']);
error_log($_GET['sort'] ?? '');
echo json_encode($this->gateway->getAllAsPageable($data)); // this returns response with json list
How to receive JSON POST with PHP, path variables, _GET
How to receive passed json body via POST request from php server request
// Takes raw data from the request
$json = file_get_contents('php://input');
// Converts it into a PHP object
$data = json_decode($json);
http status codes, json response body
200 OK
201 CREATED
204 NO CONTENT
404 NOT FOUND - in this case the http response doesnt have json body even it was sent by lets say php server
useEffect, debouncing of user input for 500 ms, cleanup function
useEffect - is runs after every component render cycle or lets say whenevery component was re-evaluated
useEffect(() => {}, []) ... this runs only for first time when component is mounted
useEffect(() => {}) ... it runs every time after component render cycle
useEffect(() => {}, [email]) ... runs whenever component was re-evaluated AND state email has changed that means it runs for first time render cycle and then waiting for typing email
DEBOUNCING
it is a technique to debounc user input to wait until user is done with typing for eg. after 500 ms
CLEANUP FUNC
it runs before every side effect function execution and it runs on first render cycle /mounting component
Example cleanup + debouncing
it ensures that for example http fetch will be not executing every time when user typing but after some delay and on first render cycle
t [formIsValid, setFormIsValid] = useState();
useEffect(() => {
const timer = setTimeout(() => {
console.log('FormIsValid');
setFormIsValid(
userId.includes('@')
);
}, 1000);
return () => {
console.log('CLEANUP');
clearTimeout(timer);
}
}, [userId]);
Example cleanup with no dependency
And cleanup func in this case would run when the component is removed
So in this case for example when I log in and component is removed from DOM we see the cleanup
It ensures that it is called after component is unmounted/removed or leaved
useEffect(() => {
console.log('EFFECT RUNNING');
return () => {
console.log('EFFECT CLEANUP');
}
}, []);
Typical errors, Uncaught runtime errors:
Cannot read properties of null (reading 'id')
Where:
<div>{props.choosedOrder.id}</div>
Cause:
choosedOrder object is null because
const [choosedOrder, setChoosedOrder] = useState(null);
How to solve?
{props.choosedOrder ? props.choosedOrder.id : null}
or
const [choosedOrder, setChoosedOrder] = useState({});
How to use promises, async, await
great takeaways guide
https://dmitripavlutin.com/javascript-fetch-async-await/
createOrder(item.choosedFlavor, item.amount)
.then(result => {
console.log(result.message)
console.log(result.id)
});
async function createOrder(flavor, amount) {
// alert(amount);
let url = `http://localhost/php-rest-api/products?note=${note}&amount=${amount}&flavor=${flavor}&user_id=${userId}`;
console.log(url);
try {
const response = await fetch(url, {
method: 'POST',
mode: 'cors', // no-cors, cors, *same-origin (cors is default)
});
if (!response.ok) {
throw new Error('something went wrong!');
}
const result = await response.json();
return result;
} catch (error) {
console.log(error.message);
}
}
React useCallback, dependency argument, only when needs to be run
const [movies, setMovies] = useState([]);
// if we would be using some external state then is better to use useCallback instead of useEffect
// but this is const object and hence we need to call it in proper order (function is visible anywhere but object must be first declared and called after its code)
const fetchMoviesHandler = useCallback(() => {
try {
let url = 'https://cat-fact.herokuapp.com/facts/';
// let url = 'https://swapi.dev/api/films/';
fetch(url).then(response => {
if (!response.ok) {
throw new Error('something went wrong here!');
}
return response.json();
}).then(data => {
const transformedMovies = data.results.map(movieData => {
return {
id: movieData.episode_id,
title: movieData.title,
openingText: movieData.opening_crawl
}
});
setMovies(transformedMovies);
console.log(transformedMovies);
console.log(data.count);
console.log('infinity?');
setMovies(data);
})
} catch(error) {
console.log(error.message);
}
}, []);//second dependency
useEffect(() => {
fetchMoviesHandler();
}, [fetchMoviesHandler]);
Javascript Hoisting, difference between function and const
Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their scope before code execution.
THis is not considered as hoisting
const someMethod = useCallback(...);
React useEffect, fetch api, try catch http response, fetchMovies function
const [movies, setMovies] = useState([]);
// second arg is dependency, when is changed then function is again reloaded
// functions are real objects and can be changed any time
// the fetchMoviesHandler function is changed (it is object) whenever the component is re-rendered (refresh page)
// therefore we dont use fetchMoviesHandler as second dependency arg
useEffect(() => {
fetchMoviesHandler();
}, []);
// this is fine but it may cause some issues if our function (fetchmovies) would be using some external state
// functions are real objects and can be change any time
function fetchMoviesHandler() {
try {
let url = 'https://swapi.dev/api/films/';
fetch(url).then(response => {
if (!response.ok) {
throw new Error('something went wrong here!');
}
return response.json();
}).then(data => {
const transformedMovies = data.results.map(movieData => {
return {
id: movieData.episode_id,
title: movieData.title,
openingText: movieData.opening_crawl
}
});
setMovies(transformedMovies);
console.log(transformedMovies);
console.log(data.count);
console.log('infinity?');
setMovies(data);
})
} catch(error) {
console.log(error.message);
}
}
How to add or remove multiple class to div component