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' }
      fetch("LOGIN_URL",
        {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(data)
        }).then(res => res.json())
        .then(data => {
          setUser(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 (
    <>
      <h1>List</h1>
      {list !== undefined ? list.map(list => (<li key={list.id}>{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.

//Form.js
import React, { useState } from 'react'

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

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

    setInput({
    ...input,
     [name]: value
  })
  }

  const handleSubmit = (e) => {
      e.preventDefault()
      console.log(input)
  }

  return (
    <form onSubmit={handleSubmit}>
        <label>Username:
        <input type="text" name="username" onChange={handleChange} /></label>
        <br/>
        <label>Password:
        <input type="text" name="password" onChange={handleChange} /></label>
        <br/>
        <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/>
      <button>Submit</button>
    </form>
  )
}

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

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.

//App.js

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

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

Finally your index.js

//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

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


let todo = ''
let todos = []

let getTodos = () => {
ipcRenderer.send('giveTodos')

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

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

let clear = () => 
{
ipcRenderer.send('clearTodos')
ipcRenderer.on('clearedTodos', () => todos = [])
}

let quit = () => {
	ipcRenderer.send('quit')
}
onMount(() => { getTodos() })
</script>

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

<style>
	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;
		}
	}
</style>
// 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.
  mainWindow.loadFile('public/index.html')

  // Open the DevTools.
  mainWindow.webContents.openDevTools()

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

// 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 (?)")
  q.run(todo)
  q.finalize()
})

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

ipcMain.on('clearTodos', (e) => {
  db.run("DELETE FROM todos")
  e.sender.send('clearedTodos')
})

Caddy Server 2 + PHP-FPM Installation on Linux

Start with downloading Caddy 2 Linux binary.

https://github.com/caddyserver/caddy/releases/download/v2.0.0-beta.17/caddy2_beta17_linux_amd64

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" \
	caddy

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

cd etc/systemd/system
wget https://raw.githubusercontent.com/caddyserver/dist/master/init/caddy.service

Go to /etc and create a caddy directory.

cd etc
mkdir caddy

Create a Caddyfile in /etc/caddy folder with sample content below.

example.com {
root * /var/www/html/
try_files {path} {path}/ /index.php?{query}
php_fastcgi unix//run/php/php7.3-fpm.sock
file_server
}

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

<script>
import Posts from './Posts.svelte';
import { onMount } from 'svelte';

let data = [];

onMount(async () => {
let response = await fetch('https://jsonplaceholder.typicode.com/posts');
data = await response.json();
});

</script>

<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

<script>
export let data;
</script>

{#each data as item}
<h1>{item.title}</h1>
<p>{item.body}</p>
{/each}

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