Skip to content

Instantly share code, notes, and snippets.

View karpolan's full-sized avatar
❤️
React + Node

Anton Karpenko karpolan

❤️
React + Node
View GitHub Profile
@karpolan
karpolan / redirect_www_add_index_html.js
Last active February 1, 2024 15:41
AWS CloudFront function for SPA, SSG and SEO. Redirects www URL to non-www URI, also adds missing `/index.html` to the link
/**
* Based on this thread https://github.com/aws-samples/amazon-cloudfront-functions/issues/11
*/
function getQueryParamsAsString(querystring) {
if (!querystring || querystring.length < 1) {
return ''; // There is no query params
}
const str = [];
for (const param in querystring) {
@karpolan
karpolan / useIsMobileNextJs.ts
Last active May 1, 2024 22:03
React useIsMobile() hook compatible with Next.js SSG/SSR
'use client';
import { useEffect, useState } from 'react';
import { useMediaQuery } from 'react-responsive';
export const IS_SERVER = typeof window === 'undefined';
export const MOBILE_SCREEN_MAX_WIDTH = 640;
export const SERVER_SIDE_MOBILE_FIRST = true; // true - for mobile, false - for desktop
/**
* Hook to detect isMobile vs. isDesktop using Media Query
@karpolan
karpolan / log.ts
Last active October 7, 2022 01:24
Simply logger for React App using TypeScript
const LOG_LEVEL_FROM_ENV = process?.env?.REACT_APP_LOG_LEVEL ?? 'silent';
/**
* Supported logging levels by names, the index is the level number.
*/
export const LOG_LEVEL_NAMES = ['trace', 'debug', 'info', 'warn', 'error', 'silent'];
/**
* Lightweight logger with minimal log level restrictions
* @class Log
@karpolan
karpolan / axios.ts
Last active October 6, 2022 22:15
Preconfigured instance of Axios to use in React Apps with TypeScript
import axios from 'axios';
import { api } from '.';
import { log } from '../utils/log';
import { addTrailingSlash } from '../utils/path';
// Note: Use Local storage to override API base path
export const API_URL = addTrailingSlash(process.env.REACT_APP_API || 'http://localhost:3030');
/**
@karpolan
karpolan / code-challenge.js
Created July 17, 2022 08:05
Some code challenge, working but not scalable well. Silver medal :)
function solution(X, Y, colors) {
let countG = 0;
let countR = 0;
let points = []
for (let i = 0; i < colors.length; i++) {
const distance = Math.sqrt(X[i]**2 + Y[i]**2)
const color = colors[i]
points.push({distance, color})
if (color === 'R') {
@karpolan
karpolan / useAxios.js
Last active October 8, 2021 17:46
useAxios() hook with separate (url, method, body, headers) params
const useAxios = ({ url, method, body = null, headers = null }) => {
const [response, setResponse] = useState(null);
const [error, setError] = useState('');
const [loading, setLoading] = useState(true);
const fetchData = () => {
axios[method](url, JSON.parse(headers), JSON.parse(body))
.then((res) => {
setResponse(res.data);
})
@karpolan
karpolan / useAxiosUniversal.js
Last active May 22, 2021 03:03
useAxios() hook with single object as axios's params
export const useAxios = (axiosParams) => {
const [response, setResponse] = useState(undefined);
const [error, setError] = useState('');
const [loading, setloading] = useState(true);
const fetchData = async (params) => {
try {
const result = await axios.request(params);
setResponse(result.data);
} catch (error) {
@karpolan
karpolan / getMetaTagContent.ts
Last active May 19, 2021 09:11
TypeScript - testing <head> meta tags
function getMetaTagContent(metaTagName: string): string | null {
const metaTags: HTMLCollectionOf<HTMLMetaElement> = document.getElementsByTagName('meta');
const nameToFind = metaTagName.toLowerCase();
for (const current of metaTags) {
if (current.getAttribute('name')?.toLowerCase() === nameToFind) {
return current.getAttribute('content');
}
}
return '';
}
@karpolan
karpolan / arraySuperSort.js
Last active February 27, 2021 22:32
Sorting of array in O(max(array)) complicity!
const source = [20, 5, 100, 1, 90, 200, 40, 29];
const sorted = [];
console.log('source:', source);
for (const value of source) {
setTimeout(() => {
sorted.push(value);
console.log('sorting:', value); // to see progress
}, value);
@karpolan
karpolan / .prettierrc.js
Last active September 13, 2024 20:14
Prettier config for React App
module.exports = {
printWidth: 120, // max 120 chars in line, code is easy to read
useTabs: false, // use spaces instead of tabs
tabWidth: 2, // "visual width" of of the "tab"
trailingComma: 'es5', // add trailing commas in objects, arrays, etc.
semi: true, // add ; when needed
singleQuote: true, // '' for stings instead of ""
bracketSpacing: true, // import { some } ... instead of import {some} ...
arrowParens: 'always', // braces even for single param in arrow functions (a) => { }
jsxSingleQuote: false, // "" for react props, like in html