React Hooks, JWT-Fetch Example

We have two states. First one is user and second one is list. In first state we are holding our user_token, token_type and expiration values.

Basically, we are running first useEffect when the page loads. It’s similar with ComponentDidMount(). We are being sure that user state is at is first state by checking with if block. Then first useEffect changes the user state by fetching user values to user state. Second useEffect is watching for changes in user state so, when user state changes it’s firing up second useEffect and it fetches our list. Also we are surrounding fetch with if block for being sure that second useEffect is not fired up when page loads first.

List holding only id and title in this example.

import React, { useEffect, useState } from 'react'

function App() {

  const [user, setUser] = useState(false)
  const [list, setList] = useState([])

  useEffect(() => {
    if (user === false) {
      let data = { email: 'LOGIN_USERNAME', password: 'LOGIN_PASSWORD' }
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(data)
        }).then(res => res.json())
        .then(data => {
        ).catch(err => console.log(err))
  }, [user])

  useEffect(() => {
    if (user !== false) {
      fetch("FETCH_LIST_URL", {
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${user.access_token}`
      }).then(res => res.json()).then(data => {
        setList([...list, data])
      }).catch(err => console.log(err))
  }, [user])

  return (
      {list !== undefined ? => (<li key={}>{list.title}</li>)) : "null"}

export default App

React Hooks/useState Form Example

Working with React Hooks is fun. In this code example, i’m basically going to show you how to create a form in functional components with useState. Also my form will include checkboxes.

import React, { useState } from 'react'

export const Form = () => {
  const [input, setInput] = useState({})

  const handleChange = (e) => { 
    let { name, value, type, checked } =
     value = type === "checkbox" ? checked : value

     [name]: value

  const handleSubmit = (e) => {

  return (
    <form onSubmit={handleSubmit}>
        <input type="text" name="username" onChange={handleChange} /></label>
        <input type="text" name="password" onChange={handleChange} /></label>
        <input type="checkbox" name="male" onChange={handleChange} />Male<br/>
        <input type="checkbox" name="female" onChange={handleChange} />Female<br/>
        <input type="checkbox" name="none"  onChange={handleChange} />None of these<br/>

In handleChange function we are checking the type of input and if input is checkbox, we’re assigning to value variable instead of

Its’a basic component example. So if you want to run this, you need to include it in your App. Here is a simple example to how to include it.


import React from 'react'
import { Form } from './Form'

function App() {
  return ( <div><Form/></div> )

Finally your index.js

//...your imports...
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
//..your imports...

ReactDOM.render(<App />, document.getElementById('root'));

Electron Svelte Todo App Example

import { onMount } from 'svelte';
const { ipcRenderer } = require('electron')

let todo = ''
let todos = []

let getTodos = () => {

ipcRenderer.on('getTodos', (e, rows) => todos = rows)

let addTodo = () => {
ipcRenderer.send('addTodo', todo)

let clear = () => 
ipcRenderer.on('clearedTodos', () => todos = [])

let quit = () => {
onMount(() => { getTodos() })

	<form on:submit|preventDefault={addTodo}>
	<input type="text" bind:value={todo}>
	<button type="submit">Save</button>
	<button on:click={clear}>Clear All</button>
	<button on:click={quit}>Exit</button>
	{#if todos.length === 0}
	There is no todos.
	{#each todos as todo}

	main {
		text-align: center;
		padding: 1em;
		max-width: 240px;
		margin: 0 auto;

	h1 {
		color: #ff3e00;
		text-transform: uppercase;
		font-size: 4em;
		font-weight: 100;

	@media (min-width: 640px) {
		main {
			max-width: none;
// Modules to control application life and create native browser window
const {app, BrowserWindow, ipcMain} = require('electron')
const path = require('path')

let sqlite3 = require('sqlite3').verbose()
let db = new sqlite3.Database('./todo.db')

const production = !process.env.ELECTRON_RELOAD;

if (!production) {
	const path = require('path');
	require('electron-reload')(__dirname, {
		electron: path.join(__dirname, 'node_modules', '.bin', 'electron'),
		awaitWriteFinish: true,

function createWindow () {
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    title: "Test App",
    show: false,
    //frame: false,
    width: 800,
    height: 600,
    webPreferences: {
      //preload: path.join(__dirname, 'public/preload.js')
      nodeIntegration: true

  // and load the index.html of the app.

  // Open the DevTools.

  mainWindow.on('ready-to-show', () => {

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', createWindow)

// Quit when all windows are closed.
app.on('window-all-closed', function () {
  // On macOS it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== 'darwin') app.quit()

app.on('activate', function () {
  // On macOS it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (BrowserWindow.getAllWindows().length === 0) createWindow()

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.

ipcMain.on('quit', app.quit)

ipcMain.on('addTodo', (e,todo) => {
  let q = db.prepare("INSERT INTO todos (todo) VALUES (?)")

ipcMain.on('giveTodos', (e) => {
  db.all("SELECT * FROM todos ORDER BY id DESC", (err, rows) => {
	  e.sender.send('getTodos', rows)

ipcMain.on('clearTodos', (e) => {"DELETE FROM todos")

Caddy Server 2 + PHP-FPM Installation on Linux

Start with downloading Caddy 2 Linux binary.

Rename it as caddy.

mv caddy2* caddy

Move file to /usr/bin

mv caddy /usr/bin/

Add a group called caddy

groupadd --system caddy

Add a user to the group

useradd --system \
	--gid caddy \
	--create-home \
	--home-dir /var/lib/caddy \
	--shell /usr/sbin/nologin \
	--comment "Caddy web server" \

Go to /etc/systemd/system/ and download caddy.service file.

cd etc/systemd/system

Go to /etc and create a caddy directory.

cd etc
mkdir caddy

Create a Caddyfile in /etc/caddy folder with sample content below. {
root * /var/www/html/
try_files {path} {path}/ /index.php?{query}
php_fastcgi unix//run/php/php7.3-fpm.sock

Install PHP-FPM

apt install php-fpm

Start and enable PHP-FPM as a service.

systemctl enable php7.3-fpm
systemctl start php7.3-fpm

Start Caddy as a service.

sudo systemctl daemon-reload
sudo systemctl enable caddy
sudo systemctl start caddy

Note that, If you’re using Ubuntu 18.04 then your php-fpm version is 7.2

Svelte Each Block/onMount Example

If you’re looking for an alternative to React, Vue, Angular, Mithril or BackboneJS, Svelte comes first as an extremely straight forward JScript framework. There is no virtual dom in Svelte and also it’s pretty fast to work with it.

Here is a simple example to show you how fun to work with Svelte.

You can get Svelte with the following command.

npx degit sveltejs/template my-svelte-project

If you get an error like me, download this zip file and extract it in a folder. Next cd in to folder and install required packages with the following command.

npm install

And run…

npm run dev

Svelte means less code. I will show you how.

Now… edit App.svelte

import Posts from './Posts.svelte';
import { onMount } from 'svelte';

let data = [];

onMount(async () => {
let response = await fetch('');
data = await response.json();


<Posts data={data}/>

This example is fetching sample json data and passing it to Posts.svelte to list it.

Create a file called Posts.svelte

export let data;

{#each data as item}

You should see how easy it is. I will post more examples soon.