<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Justin &#8211; Jaytria</title>
	<atom:link href="https://api.jaytria.com/author/source/feed/" rel="self" type="application/rss+xml" />
	<link>https://api.jaytria.com</link>
	<description>Web &#124; Technology</description>
	<lastBuildDate>Wed, 09 Feb 2022 06:08:20 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.4</generator>

<image>
	<url>https://api.jaytria.com/wp-content/uploads/2019/06/cropped-Jaytria-1-32x32.png</url>
	<title>Justin &#8211; Jaytria</title>
	<link>https://api.jaytria.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Migrating Drupal 7 to Backdrop 1.x &#8211; The Important Parts</title>
		<link>https://api.jaytria.com/2022/01/21/migrating-drupal-7-to-backdrop-1-x-the-important-parts/</link>
					<comments>https://api.jaytria.com/2022/01/21/migrating-drupal-7-to-backdrop-1-x-the-important-parts/#respond</comments>
		
		<dc:creator><![CDATA[Justin]]></dc:creator>
		<pubDate>Fri, 21 Jan 2022 03:14:56 +0000</pubDate>
				<category><![CDATA[Backdrop CMS]]></category>
		<category><![CDATA[Drupal]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Web Development]]></category>
		<category><![CDATA[Upgrading Drupal]]></category>
		<guid isPermaLink="false">https://blog.jaytria.com/?p=195</guid>

					<description><![CDATA[Backdrop promises to offer an easier upgrade process than making the jump to Drupal 9+ but it&#8217;s not without its pitfalls. Fortunately the upgrade process is not heinously difficult. This guide serves as an overview and breaks down the migration process described in the official documentation. 1. Test for Theme Compatibility The biggest change between &#8230; <p class="link-more"><a href="https://api.jaytria.com/2022/01/21/migrating-drupal-7-to-backdrop-1-x-the-important-parts/" class="more-link">Continue reading<span class="screen-reader-text"> "Migrating Drupal 7 to Backdrop 1.x &#8211; The Important Parts"</span></a></p>]]></description>
										<content:encoded><![CDATA[
<div class="wp-block-image is-style-default"><figure class="aligncenter size-full"><img fetchpriority="high" decoding="async" width="566" height="345" src="https://api.jaytria.com/wp-content/uploads/2022/01/drupalmigrationheadingsource.gif" alt="Migrating Drupal 7 to Backdrop CMS" class="wp-image-212"/><figcaption>Backdrop is designed to act as the next version of Drupal 7 but the migration process is not necessarily seamless.</figcaption></figure></div>



<p class="has-drop-cap">Backdrop promises to offer an easier upgrade process than making the jump to Drupal 9+  but it&#8217;s not without its pitfalls.</p>



<p>Fortunately the upgrade process is not heinously difficult.</p>



<p>This guide serves as an overview and breaks down the migration process described in the <a href="https://docs.backdropcms.org/documentation/upgrading-from-drupal">official documentation</a>.</p>



<h2 class="wp-block-heading">1. Test for Theme Compatibility</h2>



<p>The biggest change between Drupal 7 and Backdrop has to do with how content is displayed to the user. Any custom themes you may have may not be compatible with how Backdrop displays site data. This change allows for Backdrop to do fantastic things out of the box but it accomplishes it by adding a killer feature that Drupal 7 doesn&#8217;t have &#8212; layouts.</p>



<p>Check out the official <a href="https://docs.backdropcms.org/converting-themes">theme conversion documentation</a> for more details if your theme is not compatible with Backdrop&#8217;s theme system.</p>



<h2 class="wp-block-heading">2. Test for Module Compatibility</h2>



<p>Drupal modules will not work out of the box with Backdrop. Test each module you rely on to make sure that either the functionality it provides hasn&#8217;t either been included in Backdrop core or works as intended on the new version.</p>



<p>Many modules need only slight tweaks in order to work with Backdrop, but in the event you rely on some API features that have been altered you can find examples for how to use nearly any function and API call through <a href="https://backdropcms.org/project/examples">Backdrop&#8217;s examples module</a>.</p>



<p>The <a href="https://forum.backdropcms.org/">developer forum</a> is also very friendly if you find yourself stuck anywhere along the way.</p>



<p>The Backdrop documentation also offers more detailed information regarding <a href="https://docs.backdropcms.org/converting-modules-from-drupal">module conversion.</a></p>



<h2 class="wp-block-heading">3. Create a Copy of Your Drupal 7 Site</h2>



<p>Once you have made sure your themes and modules are compatible with Backdrop then Backdrop can handle migrating your database over pretty easily. To be as safe with your data as possible we&#8217;ll duplicate your Drupal site and migrate the duplicate over just in case something goes wrong somewhere along the way.</p>



<h3 class="wp-block-heading">Create a New Database and Admin Account</h3>



<p>You&#8217;ll need to create a new empty database, username, and password for Backdrop to use.</p>



<p>Usually this can be also be done in the server&#8217;s settings panel.</p>



<h3 class="wp-block-heading">Clone the Old Database</h3>



<p>Copy your old database into the new one that you just created for Backdrop. Use your new user with admin privileges. </p>



<p>You can accomplish this using a single command in the terminal.</p>



<pre class="wp-block-code"><code>mysqldump orig_drupal_db -u drupal_db_user --password=mYDrupalDBP@ssw0rd | mysql -u new_backdrop_user -p new_backdrop_db</code></pre>



<p>You will be asked to verify the new password and boom &#8212; a duplicated database.</p>



<h3 class="wp-block-heading">Clone the Old Drupal Site</h3>



<p>Copy every file to the new Backdrop location. This ensures that your Drupal 7 site will still work after this update should you need to reference or fall back to it in the future.</p>



<p>Use cp with the <code>-r</code> flag to deep copy the site contents. </p>



<pre class="wp-block-code"><code>cp -r ./old_drupal_location ./new_backdrop_location</code></pre>



<h3 class="wp-block-heading">Update Database Credentials</h3>



<p>In order to get the new copied Drupal site to access the new database you&#8217;ll need to use the new credentials you made. <strong>Do not run update.php</strong>. You&#8217;ll need to add the new database username and password to the settings.php file.</p>



<p>The default location for the site&#8217;s configuration file will be in:</p>



<p><code>new_backdrop_location/sites/default/settings.php</code></p>



<pre class="wp-block-code"><code>247 $databases = array (
248   'default' =&gt;
249   array (
250     'default' =&gt;
251     array (
252       'database' =&gt; 'new_backdrop_db',
253       'username' =&gt; 'new_backdrop_user',
254       'password' =&gt; 'newBackdropDBP@ssw0rd',
255       'host' =&gt; 'localhost',
256       'port' =&gt; '',
257       'driver' =&gt; 'mysql',
258       'prefix' =&gt; '',
259     ),
260   ),
261 );
</code></pre>



<p>Look for the above lines and update them with the new user and database credentials you created earlier.</p>



<h2 class="wp-block-heading">4. Turn It Off</h2>



<p>Login to your now duplicated Drupal 7 site using your old Drupal administration credentials. <code>https://mynewbackdropsite.com/user</code></p>



<p>Make sure any installed modules are compatible with Backdrop and turn off any modules that aren&#8217;t.</p>



<p><strong>Make sure the theme is set to Bartik.</strong></p>



<p>Set site to Maintenance mode and kiss Drupal goodbye.</p>



<h2 class="wp-block-heading">5. Replace Core Files</h2>



<p>Add all files from the Backdrop repository replacing the <code>core</code>, <code>themes</code>, and <code>modules</code> folders with backdrop&#8217;s <code>core</code>, <code>themes</code>, and <code>modules</code> folders etc. <strong>Take care not  to replace the <code>sites</code> folder in the update process.</strong></p>



<p><strong>Do not run update.php until the end of step 8.</strong></p>



<h2 class="wp-block-heading">6. Add Modules, Layouts, and Themes to Their Respective Folders</h2>



<p>Any modules and themes that you want to use should now be moved to the <code>new_backdrop_location/modules</code> and <code>new_backdrop_location/themes</code> folder. </p>



<p>Backdrop changes the location of your contributed modules and themes directories to the site root instead of inside the <code>sites</code> folder. This means that going forward all core files will be located within the <code>core</code> directory.</p>



<h2 class="wp-block-heading">7. Move <code>files</code> Location</h2>



<p>Move any user files from <code>new_backdrop_location/sites/default/files</code> to <code>new_backdrop_location/files</code>  </p>



<p>Create a soft link from <code>new_backdrop_location/sites/default/files</code> to <code>new_backdrop_location/files</code></p>



<pre class="wp-block-code"><code>ln -s new_backdrop_location/sites/default/files new_backdrop_location/files</code></pre>



<h2 class="wp-block-heading">8. Update Backdrop&#8217;s Configuration File</h2>



<p>Backdrop stores its configuration in a different location than Drupal.</p>



<p><code>new_backdrop_location/settings.php</code></p>



<pre class="wp-block-code"><code>  7 /**
  8  * Database configuration:
  9  *
 10  * Most sites can configure their database by entering the connection string
 11  * below. If using master/slave databases or multiple connections, see the
 12  * advanced database documentation at
 13  * https://api.backdropcms.org/database-configuration
 14  */
 15 $database = 'mysql://user:pass@localhost/database_name';
 16 $database_prefix = '';
</code></pre>



<p>Change Line 15 to include the correct database credentials.</p>



<p>While you&#8217;re in this file change <code>update_free_access</code> on Line 59 to <code>TRUE</code>. </p>



<pre class="wp-block-code"><code> 48 /**
 49  * Access control for update.php script.
 50  *
 51  * If you are updating your Backdrop installation using the update.php script
 52  * but are not logged in using either an account with the "Administer software
 53  * updates" permission or the site maintenance account (the account that was
 54  * created during installation), you will need to modify the access check
 55  * statement below. Change the FALSE to a TRUE to disable the access check.
 56  * After finishing the upgrade, be sure to open this file again and change the
 57  * TRUE back to a FALSE!
 58  */
 59 $settings&#91;'update_free_access'] = TRUE;
</code></pre>



<p>This will allow the update to proceed without needing to be logged in.</p>



<p>Save your changes to the configuration file and visit the update page:</p>



<p><code>http://mynewbackdropsite.com/core/update.php</code></p>



<p>Proceed with all the updates and before long you will be purring along with Backdrop.</p>



<h2 class="wp-block-heading">9. Secure Your Site</h2>



<p>After the update script finishes you&#8217;ll need to set <code>update_free_access</code> in the backdrop <code>settings.php</code> file back to FALSE.</p>



<p>Finally, enable your custom themes, layouts, and modules before turning off maintenance mode.</p>



<h2 class="wp-block-heading">10. Fix CRON</h2>



<p>If you have cron set up on your server you&#8217;ll need to update the location the cron job visits. The correct location will be listed at <code>https://mynewbackdropsite.com/admin/config/system/cron</code></p>



<p>Because all of Backdrop&#8217;s core files exist in the <code>core</code> folder, you&#8217;ll need to remember to include <code>/core</code> in the <code>cron.php</code> and <code>update.php</code> paths.</p>



<p>For instance the cron path is <code>https://mynewbackdropsite.com/core/cron.php?cron_key=abc123...</code></p>



<h2 class="wp-block-heading">Conclusion</h2>



<p>While Backdrop is very similar to Drupal 7, some key changes have been made to provide for the long term stability of the platform. By removing some of the cruft of Drupal 7 a few pain points in the update process may appear &#8212; particularly when using custom modules and themes. Overall though, the Backdrop foundation seeks to update the system while also maintaining as much compatibility with existing server infrastructure as possible. </p>



<p>The developers of Backdrop continue to add documentation to the site but sometimes you just need to talk to someone knowledgeable about the system. The <a href="https://forum.backdropcms.org/">forums</a> are a great place to ask project specific questions and to get help with things that you may be stuck on.</p>



<p>If you like Backdrop you can also <a href="https://backdropcms.org/news/meetings">attend community meetings</a> to get involved with the development process or contribute to the code base.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://api.jaytria.com/2022/01/21/migrating-drupal-7-to-backdrop-1-x-the-important-parts/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Adding React to Backdrop CMS: A guide for a progressively decoupled application.</title>
		<link>https://api.jaytria.com/2021/03/30/adding-react-to-backdrop-cms-a-guide-for-a-progressively-decoupled-application/</link>
					<comments>https://api.jaytria.com/2021/03/30/adding-react-to-backdrop-cms-a-guide-for-a-progressively-decoupled-application/#respond</comments>
		
		<dc:creator><![CDATA[Justin]]></dc:creator>
		<pubDate>Tue, 30 Mar 2021 23:11:30 +0000</pubDate>
				<category><![CDATA[Backdrop CMS]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[React]]></category>
		<category><![CDATA[Web Development]]></category>
		<guid isPermaLink="false">https://blog.jaytria.com/?p=170</guid>

					<description><![CDATA[Adding React to Backdrop CMS is easy enough once you understand how to do it.]]></description>
										<content:encoded><![CDATA[
<p class="has-drop-cap">Just because <a href="https://backdropcms.org">Backdrop CMS</a> is a fork of <a href="https://drupal.org">Drupal</a> doesn&#8217;t mean everything is the same. Fortunately adding React to a page is a fairly straight forward endeavor. You can walk through this project&#8217;s source code on <a href="https://github.com/jsitter/backdrop_sample_react_module">GitHub</a>.</p>



<h3 class="wp-block-heading">Module Creation</h3>



<p>There are only a few requirements to build a module for Backdrop. Inside our module&#8217;s project folder we need to make two files: a <strong>.info</strong> and a <strong>.module</strong> file</p>



<p>Our first two files will be <strong>backdrop_sample_react_module.info</strong> and <strong>backdrop_sample_react_module.module</strong>.</p>



<p><strong>backdrop_sample_react_module.info</strong></p>



<pre class="wp-block-code"><code>name = Sample React App
description = This module serves as an example of a progressively decoupled React app.
backdrop = 1.x</code></pre>



<p><strong>backdrop_sample_react_module.module</strong></p>



<pre class="wp-block-code"><code>&lt;?php

    /** Implements hook_permission().
     *  Defines permissions for your application.
     */
    function backdrop_sample_react_module_permission() {
        $permissions = array(
            'administer sample react app' =&gt; array(
                'title' =&gt; t('Administer sample React app.')),
            'sample react app user' =&gt; array(
                'title' =&gt; t('Authenticated user functions'),
            ),
        );
        return $permissions;
    }

    /**
     * Implements hook_menu().
     * AKA: Routes
     * Define your application's routes using hook_menu.
     * Define Application endpoints: POST, GET available.
     * Return JSON with: 'delivery callback' =&gt;
'backdrop_json_output',
     */
    function backdrop_sample_react_module_menu() {
        $items&#91;'sample-react-app'] = array(
            'access arguments' =&gt; array('sample react app user'),
            'description' =&gt; t('Sample application built in React for Backdrop CMS.'),
            'page callback' =&gt; 'sample_react_application_main_controller',
            'title' =&gt; t('Sample React Application'),
        );

        $items&#91;'sample-react-admin'] = array(
            'access arguments' =&gt; 'administer sample react app',
            'description' =&gt; t('Sample administration page.'),
            'page callback' =&gt; 'sample_react_application_admin_controller',
            'title' =&gt; t('Sample Admin Page'),
        );

        $items&#91;'sample-react-shared'] = array(
            'access arguments' =&gt; 'access content',
            'description' =&gt; t('Sample administration page.'),
            'page callback' =&gt; 'sample_react_application_shared_controller',
            'title' =&gt; t('Sample Shared Page'),
        );

        return $items;
    }

    /**
     * Application API Controllers
     */

    function sample_react_application_main_controller() {
        // Page visible only to authenticated users
        $page = "&lt;h1&gt;Hello Html&lt;/h1&gt;";
        return $page;
    }

    function sample_react_application_admin_controller() {
        // Page visible only to admin users
        $page = "&lt;h1&gt;Hello Admin&lt;/h1&gt;";
        return $page;
    }

    function sample_react_application_shared_controller() {
        // Page with shared authenticated and unauthenticated user experience.
        $page = "&lt;h1&gt;Hello HTML&lt;/h1&gt;";
       return $page;
    }
</code></pre>



<p>A couple things to note about our module so far is that. Our <code>.module</code> file has an opening PHP tag but no matching closing tag. This is intentional.</p>



<p> So far &#8212; we&#8217;re only doing three things with our module. First, we use <code>hook_permission()</code> to define the various access permissions for our content. Then we use <code>hook_menu()</code> to define our application&#8217;s routes. <code>hook_menu()</code> will output an array where the <strong>keys</strong> are our routes and the <strong>values</strong> are the properties associated with those routes.</p>



<p>We&#8217;re able to restrict access to any of our routes by including the <strong>&#8216;access arguments&#8217;</strong> key set to a value either defined in hook_permissions() or given by Backdrop. To allow a route to be accessible to unauthenticated users &#8212; use the permission <strong>&#8216;access content&#8217;</strong> as our route <strong>sample-react-shared</strong> does above.</p>



<p>Finally, we define our controllers. These functions are called when our authenticated users visits the routes we set up in <code>hook_menu()</code>.</p>



<p>Backdrop allows for several ways to output code to the client. Right now our controllers are outputting a vanilla string of HTML &#8212; shortly we&#8217;ll be using Backdrop&#8217;s render arrays to take advantage of some handy built-in functionality.</p>



<p>Test out your handiwork by enabling the module at <code>admin/modules/list</code> then visit the routes we made: <code>/sample-react-app</code>, <code>/sample-react-admin</code>, and <code>/sample-react-shared</code>.</p>



<h3 class="wp-block-heading">Building the React App</h3>



<p>While <strong>create-react-app</strong> is convenient, it isn&#8217;t the best way to build an app that is ready to be embedded into Backdrop. Fortunately setting up React from scratch isn&#8217;t terribly difficult.</p>



<h3 class="wp-block-heading">Installing the Dependencies</h3>



<p>Inside our module folder we&#8217;ll make a couple new folders that will house our app.</p>



<p>Lets put our app in:<br><code>backdrop_sample_react_module/js/react/sampleapp</code></p>



<p>Inside the terminal, navigate to the <code>sampleapp</code> folder and type: <code>npm<strong> </strong>init</code></p>



<p>This will build out a basic <code>package.json</code> file that lists our application dependencies and scripts.</p>



<p>React needs a toolchain to build and render your code. We&#8217;ll start by installing the development dependencies.</p>



<p><code>npm install --save-dev @babel/cli @babel/core @babel/preset-env @babel/preset-react babel-loader webpack webpack-cli</code></p>



<p>After NPM installs the required dev dependencies we can install React.</p>



<p><code>npm install react react-dom</code></p>



<h3 class="wp-block-heading">Add Webpack Config File</h3>



<p>The webpack config file contains the settings that tell webpack how to handle and compile JSX.</p>



<p>Place this code below in a file named <code>webpack.config.js</code></p>



<pre class="wp-block-code"><code>const path = require('path');
 
const config = {
 entry: './src/index.js',
 devtool: (process.env.NODE_ENV === 'production') ? false : 'inline-source-map',
 mode: (process.env.NODE_ENV === 'production') ? 'production' : 'development',
 output: {
   path: path.resolve(__dirname, 'build'),
   filename: 'app.bundle.js'
 },
 module: {
   rules: &#91;
     {
       test: /\.js$/,
       exclude: /(node_modules)/,
       use: {
         loader: 'babel-loader'
       }
     }
   ]
 },
};
 
module.exports = config;
</code></pre>



<h3 class="wp-block-heading">Edit package.json</h3>



<p>We need to add a few items to our package.json file in order to be able to build our app.</p>



<pre class="wp-block-code"><code> "scripts": {
   "build": "NODE_ENV=production webpack",
   "watch": "webpack --watch --progress"
 },</code></pre>



<p>Add the build and watch scripts to your package.json <code>scripts</code> key.</p>



<h3 class="wp-block-heading">Configure Babel</h3>



<p>We&#8217;ll need to add a babel key to our package.json file to tell Babel how to handle our application.</p>



<pre class="wp-block-code"><code> "babel": {
   "presets": &#91;
     &#91;
       "@babel/preset-env",
       {
         "targets": {
           "browsers": &#91;
             "IE &gt;= 11",
             "last 3 versions"
           ]
         }
       }
     ],
     "@babel/preset-react"
   ]
 }</code></pre>



<h3 class="wp-block-heading">Build Your App</h3>



<p>Create a folder named <code>src</code> and add a file name index.js. This is the file that our toolchain will start the build process from.</p>



<pre class="wp-block-code"><code>import React from 'react';
import { render } from 'react-dom';

const App = () =&gt; {
    return (
        &lt;div&gt;Hello React&lt;/div&gt;
    )
}

render(&lt;App /&gt;, document.querySelector('#myapp'));</code></pre>



<p>You should be able to run <code>npm run watch</code> to compile your app using development settings. Webpack will automatically watch your app&#8217;s files and recompile when they&#8217;re changed. When ready to deploy however it&#8217;s best to run <code>npm run build</code> to properly minimize the app for production.</p>



<p>Once built, you&#8217;ll see a new folder named <code>build</code>. Inside it will contain your <code>app.bundle.js</code> that we will include in our Backdrop module.</p>



<h3 class="wp-block-heading">Include Your App in Backdrop</h3>



<p>Back in our <code>.module</code> file we will need to change the output of our controller from  HTML to  a <strong>render array</strong>.</p>



<pre class="wp-block-code"><code>    function sample_react_application_main_controller() {
        // Page visible only to authenticated users
        $module_path = backdrop_get_path('module','backdrop_sample_react_module');
        $js_path = $module_path . '/js/react/sampleapp/build/app.bundle.js';
        $css_path = $module_path . '/css/styles.css';
        $page = array();
        $page&#91;'content'] = array(
            '#type' =&gt; 'markup',
            '#markup' =&gt; '&lt;div id="myapp"&gt;Hello Html&lt;/div&gt;',
            '#attached' =&gt; array(
                'js' =&gt; array(
                    array(
                        'data' =&gt; $js_path,
                        'every_page' =&gt; FALSE,
                        'group' =&gt; JS_THEME,
                        'type' =&gt; 'file',
                        'preprocess' =&gt; FALSE,
                        'scope' =&gt; 'footer',
                    )
                ),
                'css' =&gt; array(
                    array(
                        'data' =&gt; $css_path,
                        'every_page' =&gt; FALSE,
                        'group' =&gt; CSS_THEME,
                        'type' =&gt; 'file',
                        'preprocess' =&gt; FALSE,
                        )
                    ),
                ),
            );
        return $page;
    }</code></pre>



<p>Instead of outputting HTML we&#8217;ve refactored our controller to output a backdrop <a href="https://docs.backdropcms.org/api/backdrop/modules%21examples%21render_example%21render_example.module/1">render array</a>. Importantly, we need to specify our scope as &#8216;footer&#8217; in order to have our JavaScript load after the DOM elements have been loaded.</p>



<h3 class="wp-block-heading">Conclusion</h3>



<p>We&#8217;ve walked through the basic process to add React components to Backdrop CMS using progressive decoupling. This approach allows you to integrate your app without losing any of the features that make using a content management system so appealing. We don&#8217;t have to go fully headless just to use React.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://api.jaytria.com/2021/03/30/adding-react-to-backdrop-cms-a-guide-for-a-progressively-decoupled-application/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Embracing Context Switching Part One</title>
		<link>https://api.jaytria.com/2019/12/09/embracing-context-switching-part-one/</link>
					<comments>https://api.jaytria.com/2019/12/09/embracing-context-switching-part-one/#respond</comments>
		
		<dc:creator><![CDATA[Justin]]></dc:creator>
		<pubDate>Mon, 09 Dec 2019 19:19:39 +0000</pubDate>
				<category><![CDATA[Uncategorized]]></category>
		<guid isPermaLink="false">https://blog.jaytria.com/?p=132</guid>

					<description><![CDATA[Enable dual language proficiency by studying the differences and similarities between two of the hottest languages: Python and JavaScript.]]></description>
										<content:encoded><![CDATA[
<p><strong>Enable dual language proficiency by studying the differences and similarities between two of the hottest languages: Python and JavaScript.</strong></p>



<p class="has-drop-cap">Developing for the web sometimes requires a number of different skills and languages. The two worlds of JavaScript and Python have found a home in web development but they have their own idiosyncrasies. </p>



<p>Here are some of the more useful features and how they are approached with each language.</p>



<h2 class="wp-block-heading">Logging and Debugging</h2>



<figure class="wp-block-table"><table class=""><tbody><tr><th>JavaScript</th><th>Python</th></tr><tr><td><code>console.log("hello");<br>console.info("This is some info");</code><br><code>console.warn("This is a warning");</code><br><code>console.dir(Object);  // Show methods</code><br></td><td><code>print("This will log to console")</code><br><code>dir(object) // Show Methods</code></td></tr></tbody></table></figure>



<h2 class="wp-block-heading">Unit Testing</h2>



<figure class="wp-block-table"><table class=""><tbody><tr><th>JavaScript</th><th>Python</th></tr><tr><td>Mocha<br>Chai<br><a href="https://geekflare.com/javascript-unit-testing/">Many More&#8230;</a></td><td>unittest<br>Pytest</td></tr></tbody></table></figure>



<p>JavaScript doesn&#8217;t come with a native way to test code, but there are a plethora of 3rd party libraries to choose from when you want to make certain your code continues to function. Mocha and Jest are some of the most popular to choose from. </p>



<p>The Python Standard Library on the other hand includes <a href="https://docs.python.org/3/library/development.html">a number of development tools</a> including automatic documentation generation and unit testing to help with developing and maintaining your application. </p>



<p>While <code>unittest</code> is included in the Python, there are 3rd party suites and tools that can help provide better performance and error reporting. Tools like <code>pytest</code> and <code>selenium</code> seek to improve on the experience provided by the built-in testing tools.</p>



<h2 class="wp-block-heading">Data Types</h2>



<figure class="wp-block-table"><table class=""><tbody><tr><th>JavaScript</th><th>Python</th></tr><tr><td>Boolean, Number, String, Null, Undefined</td><td>Boolean, Integer, Float, String, Complex</td></tr></tbody></table></figure>



<p>In JavaScript both <code>null</code> and <code>undefined</code> are primitive data types.</p>



<p>Running the following code:</p>



<pre class="wp-block-code"><code>typeof(null);
typeof(undefined);</code></pre>



<p>JavaScript will respond:</p>



<pre class="wp-block-code"><code>"object"
"undefined"</code></pre>



<p>In Python, complex numbers can be represented using their own data type. A complex number (also known as an imaginary number) <a href="https://en.wikipedia.org/wiki/Complex_number">is a number whose root is -1</a>. </p>



<p>Using complex numbers is pretty straight forward. Python uses <code>j</code> to represent the imaginary part of the complex number.</p>



<pre class="wp-block-code"><code>my_complex_number = 4+3j
print(type(my_complex_number))</code></pre>



<p>You should see the output:</p>



<pre class="wp-block-code"><code>&lt;class 'complex'></code></pre>



<h2 class="wp-block-heading">Exception Handling</h2>



<figure class="wp-block-table"><table class=""><tbody><tr><th>JavaScript</th><th>Python</th></tr><tr><td>try&#8230;catch</td><td>try &#8230; except</td></tr></tbody></table></figure>



<p>The syntax between JavaScript and Python is just different enough to be confusing.</p>



<p>JavaScript will pass in an object with several methods. This can help you to debug the error that has occurred. </p>



<pre class="wp-block-code"><code>try {
   // Try some fancy thing here
} catch (error) {
  // This block is run if an error occurs
  console.warn(error.message)
}</code></pre>



<p>Python&#8217;s syntax on the other hand:</p>



<pre class="wp-block-code"><code>try:
  # Try some fancy Python code here
except ValueError:
  # This block runs if a specific ValueError has been encountered
except:
  # This block will run if a different error is thrown

</code></pre>



<p>Python allows for many more ways to handle errors. For a more in depth look at error handling in Python <a href="https://docs.python.org/3/tutorial/errors.html">check out the docs</a>.</p>



<h2 class="wp-block-heading">Variables</h2>



<figure class="wp-block-table"><table class=""><tbody><tr><th>JavaScript</th><th>Python</th></tr><tr><td>Declared using <code>let</code>, <code>const</code>, or <code>var</code></td><td>Assignment Only</td></tr></tbody></table></figure>



<p>Python and JavaScript handle variable assignment in strikingly different ways though it may not be immediately obvious.</p>



<p>Newer versions of JavaScript allow you to be more selective about where your variables are accessible via the <code>let</code> keyword. <code>let</code> confines the scope of your variable assignments to the block in which it is created. </p>



<pre class="wp-block-code"><code>for(let i=0;i&lt;2;i++){
  let myVar = "Block Scope Variable ";
  console.log(myVar+i);
}
console.log(myVar);</code></pre>



<pre class="wp-block-preformatted">Block Scope Variable 0
Block Scope Variable 1
 /home/justin/Projects/testing/jtest.js:5
   console.log(myVar);
               ^
ReferenceError: myVar is not defined</pre>



<p>Using <code>let</code> protects the variables <code>myVar</code>  and <code>i</code> from being accessed from outside of the block they were declared. Python on the other hand has no such feature. Python will not prevent you from accessing any values if you really have the desire. Because of this, it&#8217;s customary to prefix functions, methods, and variables that are meant to be private using an underscore. </p>



<p>There&#8217;s another key difference related to JavaScript&#8217;s implicit functionality as well.</p>



<h3 class="wp-block-heading">Hoisting in JavaScript</h3>



<p>JavaScript</p>



<pre class="wp-block-code"><code>console.log(myMessage);
var myMessage = "Hello World!";</code></pre>



<p>Due to <a href="https://developer.mozilla.org/en-US/docs/Glossary/Hoisting">hoisting</a>, the code above will work fine and outputs <code>undefined</code> to the console. JavaScript will only hoist variable declarations. As you can see, any assignments that happen will occur where you would expect in your code.</p>



<p>Hoisting also only occurs when using the <code>var</code> keyword. Variables declared using <code>let</code> or <code>const</code> are not hoisted at all and will throw an error <code>myVar is not defined</code> instead of just logging <code>undefined</code> to the console.</p>



<h2 class="wp-block-heading">Spread and Splat</h2>



<figure class="wp-block-table"><table class=""><tbody><tr><td><strong>JavaScript</strong></td><td><strong>Python</strong></td></tr><tr><td><code>...</code> (spread)</td><td><code>*</code> (splat)</td></tr></tbody></table></figure>



<p>JavaScript and Python have similar tools for unpacking lists or iterables into 0 or more values.</p>



<p>JavaScript Example:</p>



<pre class="wp-block-code"><code>let myList = [1,2];

function myFunc(param1, param2){
  console.log(param1 + param2);
}

myFunc(...myList);</code></pre>



<p>Python Example:</p>



<pre class="wp-block-code"><code>paramList = [1,2]
def addTwo(param1, param2):
  print(param1 + param2)

addTwo(*paramList)</code></pre>



<p>Both of these functions will output the value <code>3</code>.</p>



<h2 class="wp-block-heading">Loops</h2>



<figure class="wp-block-table"><table class=""><tbody><tr><th>JavaScript</th><th>Python</th></tr><tr><td><code>for</code><br><code>for/in</code><br><code>for/of</code>&nbsp;<br><code>while</code><br><code>do/while</code></td><td><code>while</code>/<code>else </code><br><br><code>for in</code><br>using: <code>range()</code>, <code>enum()</code> and an iterator object.</td></tr><tr><td><code>Array.map()</code><br><code>Array.prototype.forEach()</code><br></td><td>List Comprehensions<br>Instead of: <br><code>mylist = [1,2,3,4,5]<br>for x in mylist:<br>    print(x)<br></code>Use: <br><code>[ print(x) for x in mylist]</code><br></td></tr></tbody></table></figure>



<p>There are many ways to create loops in both languages. In addition to C style loops, JavaScript adds additional ways to iterate over arrays, maps, and sets with built in methods which use callbacks.</p>



<h2 class="wp-block-heading">Functions</h2>



<figure class="wp-block-table"><table class=""><tbody><tr><th>JavaScript</th><th>Python</th></tr><tr><td><code>function</code> keyword</td><td><code>def</code> keyword</td></tr><tr><td><code>(param1, param2) =&gt; expression </code></td><td><code>lambda <em>param1, param2 </em>: <em>expression</em></code></td></tr></tbody></table></figure>



<p>JavaScript and Python both allow for multiple ways to declare functions. </p>



<p>The typical way in JavaScript:</p>



<pre class="wp-block-code"><code>function foo(bar1, bar1){
  console.log(bar1 + bar2);
}</code></pre>



<p>and Python:</p>



<pre class="wp-block-code"><code>def foo(bar1, bar2):
  print(bar1 + bar2)</code></pre>



<p>Each can be represented using an anonymous function.</p>



<p>JavaScript: <code>(bar1,&nbsp;bar2)<strong>=&gt;</strong>console.log(bar1&nbsp;+&nbsp;bar2);</code></p>



<p>Python: <code><strong>lambda</strong>&nbsp;bar1,&nbsp;bar2&nbsp;:&nbsp;print(bar1,&nbsp;bar2)</code></p>



<p>Only JavaScript uses hoisting to allow the invoking of functions before they are declared. Python requires functions to be declared before they&#8217;re used.</p>



<p>The implicit behavior particular to JavaScript is that it binds <code>this</code> to different things. <code>this</code> could refer to the local execution context, or it could refer to the invoking functions namespace. Check out <a href="https://codeburst.io/all-about-this-and-new-keywords-in-javascript-38039f71780c">this great article</a> describing the different ways JavaScript handles binding <code>this</code> for each of the functions you choose.</p>



<h2 class="wp-block-heading">Generator Functions</h2>



<p>Both JavaScript and Python allow the use of generator functions. These save time and memory when working with large amounts of data by allowing the return of a single value at a time instead of storing copies in memory before returning to the invoking function. </p>



<p>The following is an example of how to use generators in both JavaScript and Python.</p>



<p>JavaScript iterators and generators are explained in detail on <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators">MDN</a>.</p>



<p>Hackaday has a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators">great article</a> explaining the difference between iterators and generators in Python.</p>



<h2 class="wp-block-heading">Conclusion</h2>



<p>This is far from an exhaustive list of all the features included in Python and JavaScript but it gives a taste of the subtle differences between the languages. Part Two will cover tools to solve common problems using appropriate language features and data structures.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://api.jaytria.com/2019/12/09/embracing-context-switching-part-one/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Using Context in React</title>
		<link>https://api.jaytria.com/2019/10/24/using-context-in-react/</link>
					<comments>https://api.jaytria.com/2019/10/24/using-context-in-react/#respond</comments>
		
		<dc:creator><![CDATA[Justin]]></dc:creator>
		<pubDate>Thu, 24 Oct 2019 21:43:04 +0000</pubDate>
				<category><![CDATA[Uncategorized]]></category>
		<guid isPermaLink="false">https://blog.jaytria.com/?p=114</guid>

					<description><![CDATA[React 16.8 adds new features including Context. This post describes in simple terms how to use context in a React application.]]></description>
										<content:encoded><![CDATA[
<figure class="wp-block-image"><img decoding="async" width="1024" height="768" src="https://blog.jaytria.com/wp-content/uploads/2019/10/IMG_1768-1024x768.jpg" alt="" class="wp-image-123" srcset="https://api.jaytria.com/wp-content/uploads/2019/10/IMG_1768-1024x768.jpg 1024w, https://api.jaytria.com/wp-content/uploads/2019/10/IMG_1768-300x225.jpg 300w, https://api.jaytria.com/wp-content/uploads/2019/10/IMG_1768-768x576.jpg 768w, https://api.jaytria.com/wp-content/uploads/2019/10/IMG_1768.jpg 1280w" sizes="(max-width: 767px) 89vw, (max-width: 1000px) 54vw, (max-width: 1071px) 543px, 580px" /><figcaption> Context in React allows you to keep your data compartmentalized in stores.</figcaption></figure>



<p>Along with React 16.8 came a plethora of new features including the ability to subscribe to a central data repository or <strong>context</strong>. There are many tutorials to follow to learn how to use context, but this one sets out to make it as simple as possible. A <a href="https://github.com/JSitter/react-hooks-context-example/">repository exists</a> that shows these topics in a working app.</p>



<p>Many of the features available now in React seem similar to features that exist in frameworks like Redux which are frequently built into React applications.</p>



<p>Unfortunately using a data store means that you&#8217;ll  increase your code complexity  slightly but it can have advantages when your application is large enough to require a central data repository for certain values.</p>



<h2 class="wp-block-heading">High Level Overview</h2>



<p>In order to use a data store we&#8217;ll need these three things.</p>



<ol class="wp-block-list"><li>Context &#8211; The source where the data and its setters reside.</li><li>Provider &#8211; The class that provides access to the context.</li><li>Consumer &#8211; This is the class that will get access to the context.</li></ol>



<p>These are the only three things that we need in order to work with contexts.</p>



<h2 class="wp-block-heading"> Create a Context</h2>



<pre class="wp-block-code"><code>import React from 'react';

// First we need a new Context
export const CounterContext = React.createContext();</code></pre>



<p>As you can see we can get a new context from the <code>React</code> import. I&#8217;m exporting <code>CounterContext</code> because I will be using it later in our counter example.</p>



<p>You may want to put your contexts in a central place in your application.  In the <a href="https://github.com/JSitter/react-hooks-context-example/">demonstration repository</a> I put my context files in <code>src/store</code>. </p>



<h2 class="wp-block-heading">Create a Provider</h2>



<pre class="wp-block-code"><code>// Next we need a provider 
export class CounterProvider extends Component { 
  state = { 
    counter: 0 
  }; 
  render() { 
    return (
      &lt;CounterContext.Provider value={{
        state: this.state,
        addCount: () => this.setState({ counter: this.state.counter + 1 }),        
        subCount: () => this.setState({ counter: this.state.counter - 1 }) 
       }}> 
        {this.props.children} 
      &lt;/CounterContext.Provider> 
    ); 
  } 
}</code></pre>



<p>Both the context and the provider should be in the same file above but I have it separated here for clarity. Refer to the <a href="https://github.com/JSitter/react-hooks-context-example/">repository</a> if you have any questions.</p>



<p>Our <strong>provider</strong> needs a <strong>context</strong> to provide to a consumer.  The provider requires  an attribute named <code>value</code> that will be made available to any consumers of the context.</p>



<p>Fortunately <code>value</code> can be anything and in the code above I have included setters that allow us to easily update our state . There are many ways to approach building applications and certain people may want to use a Store for more complicated projects but that is beyond the scope of this article.</p>



<h2 class="wp-block-heading">Consume the Values</h2>



<p>Next, let&#8217;s create our consumer. This is the <code>Counter</code> component created in <code>src/components/Counter.js</code>.</p>



<pre class="wp-block-code"><code>import React from 'react';
import {CounterContext} from '../store/simpleContext';

function Counter(){
  return(
    &lt;div>
      &lt;CounterContext.Consumer>
        {(context)=>(
          &lt;div>
            &lt;p>Count: {context.state.counter}&lt;/p>
            &lt;button onClick={context.addCount}>+&lt;/button>
            &lt;button onClick={context.subCount}>-&lt;/button>
          &lt;/div>
        )
        }
      &lt;/CounterContext.Consumer>
    &lt;/div>
  )
}

export default Counter;</code></pre>



<p>As you can see getting information out of a context is a little more work than getting it from props. First we have to create a consumer from the context we just made ( using <code>CounterContext.Consumer</code>.  Then we need to pass the context in as a function parameter to component that will be built.</p>



<p>This is our consumer, but we still need to wrap this component in a provider.</p>



<p>In <code>App.js</code> we use our counter that we made. It is here that we need to wrap <code>Counter</code> in the context provider.</p>



<pre class="wp-block-code"><code>import React from 'react';
import {CounterProvider} from './store/simpleContext';
import Counter from './components/Counter';

function App() {
  return (
    &lt;div className="App">
      &lt;CounterProvider>
        &lt;Counter/>
      &lt;/CounterProvider>
    &lt;/div>
  );
}

export default App;</code></pre>



<p>At this point you should have everything you need to get context working in React. Unfortunately using context adds  more complexity to your project so it&#8217;s a design decision that must be made carefully. Having said that,  it also allows for a more intuitive flow and compartmentalization of data. If you find that you&#8217;re having to pass props around in a deeply nested component tree you may want to think about using context to help you out. </p>
]]></content:encoded>
					
					<wfw:commentRss>https://api.jaytria.com/2019/10/24/using-context-in-react/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>How to Use State in Functional Components in React 16.8</title>
		<link>https://api.jaytria.com/2019/06/27/web-technology/</link>
					<comments>https://api.jaytria.com/2019/06/27/web-technology/#respond</comments>
		
		<dc:creator><![CDATA[Justin]]></dc:creator>
		<pubDate>Thu, 27 Jun 2019 21:10:03 +0000</pubDate>
				<category><![CDATA[Uncategorized]]></category>
		<guid isPermaLink="false">https://blog.jaytria.com/?p=76</guid>

					<description><![CDATA[React 16.8 gives developers much more freedom when it comes to functional components. Small and lightweight functional components have only had a subset of the features available to components made with classes. That is until now. In addition to allowing state, functional components have access to the equivalent of component lifecycle methods as well. This &#8230; <p class="link-more"><a href="https://api.jaytria.com/2019/06/27/web-technology/" class="more-link">Continue reading<span class="screen-reader-text"> "How to Use State in Functional Components in React 16.8"</span></a></p>]]></description>
										<content:encoded><![CDATA[
<h4 class="wp-block-heading"><strong>React 16.8 gives developers much more freedom when it comes to functional components.</strong></h4>



<div class="wp-block-image"><figure class="aligncenter is-resized"><img decoding="async" src="https://blog.jaytria.com/wp-content/uploads/2019/06/UNADJUSTEDNONRAW_thumb_5e5-1024x768.jpg" alt="React 16.8 will change the landscape of React components forever." class="wp-image-78" width="636" height="474"/><figcaption>React 16.8 will change the landscape of React components forever.</figcaption></figure></div>



<p class="has-drop-cap">Small and lightweight functional components have only had a subset of the features available to components made with classes. That is until now. In addition to allowing state, functional components have access to the equivalent of component lifecycle methods as well. This allows the same amount of control while requiring less code.</p>



<p>In React 16.8 they added features that functional components have been lacking for quite some time. In addition, more functionality which have been the domain of 3rd party libraries such as Redux, also get baked right in.</p>



<p>This article will take a look at how to use state and lifecycle methods inside functional components to reduce the complexity and repetition of your code. In a later article I will also cover contexts and how to avoid prop drilling. Let&#8217;s get started.</p>



<h2 class="wp-block-heading">State in Functional Components </h2>



<p>Prior to React 16.8, if we wanted a component to have state it needed to be written as a class. Now we can use state in functional components as well. First you&#8217;ll need to import <code>useState</code> from <code>react</code>.</p>



<pre class="wp-block-code"><code>import React, { useState } from 'react';</code></pre>



<p><code>useState</code> is a function. This is what we&#8217;ll need in order to add state to our functional component.</p>



<pre class="wp-block-code"><code>const [count, setCount] = useState(0);</code></pre>



<p><code>useState</code> is called with the initial value that state should be set at. In the line above we&#8217;re setting our initial count value to <code>0</code>.</p>



<p>What is returned when we call <code>useState</code> is an array where the first element is the value for state and the second element is a setter for it.</p>



<p>The example above uses <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment">Javascript array destructuring</a> to set the state value to <code>count</code> and the setter to <code>setCount</code>.</p>



<h3 class="wp-block-heading">Using State</h3>



<p>When you want to use state you can just reference the value in the state variable you chose. In the above example it is <code>count</code>. You can use it inside the JSX output of your function  by simply using the curly braces: <code>{count}</code></p>



<pre class="wp-block-code"><code>&lt;p>Current Count: {count}&lt;/p></code></pre>



<p>In order to update our count we can just make a call to our setter <code>setCount</code>.</p>



<pre class="wp-block-code"><code>&lt;button onClick={ ()=> setCount(count + 1)}>Change Count&lt;/button></code></pre>



<p>So far an entire functional component with state looks like this:</p>



<pre class="wp-block-code"><code>import React, { useState } from 'react';

function Counter(){
  const [count, setCount] = useState(0);
  return (
    &lt;div>
      &lt;p>Current Count: {count}&lt;/p>
      &lt;button onClick={()=> setCount(count + 1)}>Change Count&lt;/button>
    &lt;/div>
  )
}
export default Counter;</code></pre>



<h2 class="wp-block-heading">Lifecycle Methods in Functional Components</h2>



<p>In addition to state, we can also have the same control that we did with all those lifecycle methods only now in our functional components. Because it&#8217;s often required to duplicate code across several component lifecycle methods,  React developers devised a clever, simpler system to use.</p>



<p>This is where we introduce <code>useEffect</code>.</p>



<pre class="wp-block-code"><code>import React, { useEffect } from 'react';</code></pre>



<p>The way to use this new function may not be entirely obvious at first but I&#8217;ll walk through the various ways to use it effectively.</p>



<p>The basic use case is here:</p>



<pre class="wp-block-code"><code>useEffect(()=>{
  // This gets run as you would expect with componentDidUpdate
  // and componentDidMount
})</code></pre>



<p>Call <code>useEffect</code> with the initial value you want your state to be. It takes care of all the code that you would normally put into the <code>compontDidUpdate</code> and <code>componentDidMount</code> methods but instead consolidates it into a single function thereby reducing the amount of code your application needs.</p>



<p>While this may be useful for most of your applications, if you only want to run code   when a particular value changes then you can pass in a second parameter &#8212; an array with the state to watch. In addition, any stateful values your code needs to access should be passed in this way to ensure that your code has access to the latest value.</p>



<pre class="wp-block-code"><code>useEffect(()=>{
  // This is run only when the values for state that are passed in change.
  // All state used by this function must be passed in together
  // to insure that it is current.
}, [someStateValue, someOtherStateValue])</code></pre>



<h3 class="wp-block-heading">Cleanup</h3>



<p>Sometimes you need to do an action when your component unmounts such as remove listeners. <code>useEffect</code> gives us a way to do this as well.</p>



<p>The function that is passed into <code>useEffect</code> must either return a function or else nothing at all. </p>



<p>The returned function is only called when the component unmounts.</p>



<p>Here&#8217;s an example.</p>



<pre class="wp-block-code"><code>useEffect(()=>{
  // This is called when the component updates.
  return ()=>{
    // This anonymous function gets called when the component will unmount.
    // This is where you would remove any listeners etc...
  }
}) </code></pre>



<h2 class="wp-block-heading">Additional Features</h2>



<p>In addition to adding features to functional components, React 16.8 takes aim at Redux by building within React ways to store state globally that prevent us from needing to prop drill down into deeply nested components.</p>



<p>The next article will go over how to use Context in React to replace the features of Redux.</p>



<p></p>
]]></content:encoded>
					
					<wfw:commentRss>https://api.jaytria.com/2019/06/27/web-technology/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>

<!--
Performance optimized by W3 Total Cache. Learn more: https://www.boldgrid.com/w3-total-cache/

Page Caching using Disk: Enhanced 
Content Delivery Network via N/A
Lazy Loading (feed)
Minified using Disk
Database Caching using Disk (Request-wide modification query)

Served from: api.jaytria.com @ 2026-05-03 17:36:05 by W3 Total Cache
-->