<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Chukwunazaekpere </title>
    <description>The latest articles on DEV Community by Chukwunazaekpere  (@chukwunazaekpere).</description>
    <link>https://dev.to/chukwunazaekpere</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F701720%2Fd9b5ec3c-caa7-44eb-9acd-874d659357db.jpeg</url>
      <title>DEV Community: Chukwunazaekpere </title>
      <link>https://dev.to/chukwunazaekpere</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/chukwunazaekpere"/>
    <language>en</language>
    <item>
      <title>Deploying Multiple NodeJS Servers on a Single DigitalOcean Droplet; Managed by PM2, Without Using an ecosystem.config.js file</title>
      <dc:creator>Chukwunazaekpere </dc:creator>
      <pubDate>Wed, 05 Oct 2022 17:17:26 +0000</pubDate>
      <link>https://dev.to/chukwunazaekpere/deploying-multiple-nodejs-servers-on-digitalocean-managed-by-pm2-without-an-ecosystemconfigjs-file-1i6d</link>
      <guid>https://dev.to/chukwunazaekpere/deploying-multiple-nodejs-servers-on-digitalocean-managed-by-pm2-without-an-ecosystemconfigjs-file-1i6d</guid>
      <description>&lt;p&gt;Firtly, my servers are nginx-based and certified by certbot - let's encrypt. Hence, I'm assuming you're acquainted with this setup. Now, unto the epicenter of our problem.&lt;br&gt;
A major problem using the prescribed (best-practise) procedure for deploying several NodeJS server instances on digitalOcean (referred to as DO hereafter), is that; environment variables become difficult to locate; once the server is started. This becomes a bigger trouble when there are more than one servers, to be used on a single droplet. I circumvented through this challenge, by                                                   doing the following;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;a) Create various folders, on DO named w.r.t how you'd like PM2 to identify these servers; i.e. if you've got 3 servers to deploy on a single droplet, you'd say;
e.g plutonium_server, neptunium_server, promethium_server

b) clone your repo into each folder: git clone https://github.com...

c) cd into the repo; sudo nano package.json

d) in your start script, enter: "pm2 start &amp;lt;your start file&amp;gt;"
e.g: "pm2 start ./backend/dist/index.js"

ensure your package.json file has got an engines object; (recommended for deployment)
e.g engines: {
                "node": "18.1.0",
                "yarn": "1.22.18"
             }

e) save the file by saying; 
ctrl + x then shift + y then enter

f) install your project dependencies; yarn install

g) copy your environment variables; create the environment variable file as you have it locally 
e.g: cd backend/src/config &amp;amp;&amp;amp; sudo nano .env

h) copy and paste the contents of the local env-file into the newly server .env file you can call the env file whatever 

name you perceive; but as programmed locally. Just ensure the extension is appended. Repeat step e.

i) spin the server: yarn start

j) rename the server: pm2 restart 0 --name plutonium_server

k) you can now run pm2 logs or pm2 list for monitoring

l) subsequently, all you need do next time is: pm2 start plutonium_server, pm2 stop plutonium_server etc

m) replicate this procedure; to deploy other instances.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Thanks for reading.&lt;/p&gt;

</description>
      <category>pm2</category>
      <category>node</category>
      <category>servers</category>
      <category>env</category>
    </item>
    <item>
      <title>Custom Routes In Flask Using Flask Restful</title>
      <dc:creator>Chukwunazaekpere </dc:creator>
      <pubDate>Mon, 25 Jul 2022 12:04:00 +0000</pubDate>
      <link>https://dev.to/chukwunazaekpere/custom-routes-in-flask-using-flask-restful-4imj</link>
      <guid>https://dev.to/chukwunazaekpere/custom-routes-in-flask-using-flask-restful-4imj</guid>
      <description>&lt;p&gt;In this short tutorial, I'll illustrate how we can use flask to write an API; with the following goals:&lt;br&gt;
a) Defining custom routes &lt;br&gt;
b) Separating routes, controllers, models, validators etc into their respective folders&lt;/p&gt;

&lt;p&gt;I'll at a later time put up a post to aid us in understanding my style of architecture, when it comes to Flask.&lt;br&gt;
&lt;b&gt;Defining Custom Route&lt;/b&gt;&lt;br&gt;
Let's take a hypothetical blog-site for instance. I'm assuming in your project you've got a users, comments and posts folder. The reason for this, bothers on the fact that you'd want to separate the models, routes, controllers etc for posts and users. Your users controllers would definitely concern, but not limited to; registration, login, forgot-password, change-email, etc. While those for posts would include edit-post, delete-post, create-post etc. You would agree with me that clustering this transactions in one file, would definitely wear you out, if not possibly, get you insane. FurhterMore, since Flask-Restful only supports the known HTTP-verbs, "GET", "POST" etc it'd as well not sound manageable, to define new classes for each post, delete etc operations respectively. One would think that to achieve a login and register transaction would require different classes as below (in your routes.py file);&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;routes.py
class LoginView(Resource):
    logging.basicConfig(level=logging.INFO)
    logging.info("Entered the LoginView...")

    def login(self):
        print("\n\t Login route....")

class RegisterView(Resource):
    logging.basicConfig(level=logging.INFO)
    logging.info("Entered the RegisterView...")

    def register(self):
        print("\n\t Register route....")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This problem can simply be solved, pythonically, as below;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from flask_restful import (
    Resource,
    request
)
import logging

from ..models.models import Users
class AuthViews(Resource):
    logging.basicConfig(level=logging.INFO)
    logging.info("Entered the auth views...")

    def login(self):
        print("\n\t Login route....")


    def register(self):
        print("\n\t Register route....")


    def post(self):
        print("\n\t Login-Data: ", request.data)
        print("\n\t Login-Data: ", request.url)
        url = request.url
        if "login" in url:
            login = self.login()
        elif "register" in url:
            register = self.register()
        elif "forgot-password" in url:
            register = self.forgot_password()
        else:
            etc....

auth_routes = ["/auth/register", "/auth/login"]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then in your app.py file, you'd register your resource like so;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;...
from routes.routes import AuthViews, auth_routes
app = Flask(__name__)
api = Api(app)
api.add_resource(AuthViews, *auth_routes)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Thanks. Next, I'll show you how to define models, using PyMongo.&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Deploying a MERN (Typescript) project: on Digitalocean, Netlify and Mongo-atlas; with custom domains.</title>
      <dc:creator>Chukwunazaekpere </dc:creator>
      <pubDate>Mon, 30 May 2022 10:15:08 +0000</pubDate>
      <link>https://dev.to/chukwunazaekpere/deploying-a-mern-typescript-project-on-digitalocean-netlify-and-mongo-atlas-with-custom-domains-48m1</link>
      <guid>https://dev.to/chukwunazaekpere/deploying-a-mern-typescript-project-on-digitalocean-netlify-and-mongo-atlas-with-custom-domains-48m1</guid>
      <description>&lt;p&gt;Hi. It's been a while. With this post, I'll be teaching you how to deploy a MERN-Typescript application; with what I call &lt;b&gt;'branched deployment'&lt;/b&gt; and using your preferred domain names on these servers. I'm a fullstack developer; hence; efficiency and optimisation is my watch-word. The 'branched deployment simply imply, that; I've got the backend (built with NodeJS-Express) seated at digitalocean; the frontend (built with ReactJS) seated at netlify's server and my database (MongoDB) seated at Mongo-atlas. Crazy, right?&lt;br&gt;
Now; there are definitely great advantages with the 'branch deployment'; these advantages simply rests on the basis of having a loosely-coupled system, which ensures a tightly secured sequence for all sides (BE, FE and DB) of the application. So, to reach my backend, you'd need my security sequence, which is different for the frontend(FE) as well as database(DB); as compared to having everything at a place where if I could access the security sequence, then I've got full control of all sides. With this mode of deployment, manageability, optimisation, reduction in downtime, elimination of the 'series-effect' and more are some of the priviledges which this mode earns a fullstack-developer and most importantly, sanity. The series-effect happens, when a code-break in the FE, BE or DB at anytime in development or production, affects every sides of the application. But, with this mode of deployment, that can never be observed. This is not to say that there aren't disadvantages to this mode of deployment. However, the trade-offs are worth it, for the magnitude of advantages being earned. Secondly, this mode is what I'd recommend for teams. &lt;br&gt;
    I'll discuss in a separate post, how to follow on this mode of deployment from development stage; so as to achieve this purpose. But, for now, I'll assume the following;&lt;br&gt;
&lt;b&gt;1)&lt;/b&gt; You've got the application prepared and ready to deploy.&lt;br&gt;
&lt;b&gt;2)&lt;/b&gt; You've got your functioning account on all these servers; DigitalOcean, Netlify, Mongo-Atlas&lt;br&gt;
&lt;b&gt;3)&lt;/b&gt; You're acquainted with Linux commands; as this would enable you control your linux server from your workstation (or local IDE), rather than DO's bash or your dashboard.&lt;br&gt;
I'll make this post a series; so as not to make it tiring for anyone who loves to follow this path of deployment. Firstly; I'll discuss the deployment sequence of the backend (server). The following are the procedures towards the proper deployment of the server;&lt;br&gt;
&lt;b&gt;a)&lt;/b&gt; SSH activation of our droplet, to enable us remotely communicate to the droplet from our IDE&lt;br&gt;
&lt;b&gt;b)&lt;/b&gt; Creating another root user, updating and upgrading the linux (Ubuntu OS).&lt;br&gt;
&lt;b&gt;c)&lt;/b&gt; Installing current or required version of NodeJS and yarn&lt;br&gt;
&lt;b&gt;d)&lt;/b&gt; Git-clonning the repo where our project has been pushed to our droplet&lt;br&gt;
&lt;b&gt;e)&lt;/b&gt; Creating as well as hiding our environment (*.env) files on the droplet&lt;br&gt;
&lt;b&gt;f)&lt;/b&gt; Installing the pm2-package, and editing our package.json file so as to start the application with the package.&lt;br&gt;
&lt;b&gt;g)&lt;/b&gt; Installing the node_modules (package dependencies) of our application&lt;br&gt;
&lt;b&gt;h)&lt;/b&gt; Installing Nginx to enable us create custom-domains for our FE and DB&lt;br&gt;
&lt;b&gt;i) Securing our BE with certbot&lt;br&gt;
There's a whole lot; that I know. But; I'll take it gradual as much as I can; with the required illustrations where necessary. That should do for now; please, stay tuned for the updates to follow. Thanks&lt;/b&gt;&lt;/p&gt;

</description>
      <category>devops</category>
      <category>node</category>
      <category>typescript</category>
      <category>react</category>
    </item>
    <item>
      <title>Writing Custom Routes in Django RestFrameWork (DRF) Viewsets.</title>
      <dc:creator>Chukwunazaekpere </dc:creator>
      <pubDate>Wed, 01 Dec 2021 09:31:38 +0000</pubDate>
      <link>https://dev.to/chukwunazaekpere/writing-custom-routes-in-django-restframework-drf-viewsets-3pj1</link>
      <guid>https://dev.to/chukwunazaekpere/writing-custom-routes-in-django-restframework-drf-viewsets-3pj1</guid>
      <description>&lt;p&gt;Django RestFrameWork (DRF) has proven to be the most valuable and helpful library for Django. It's viewset capability is an admirable resource to enable backend devs define robust urls with embedded route structures. These routes would have required you to write a unique url; but thanks to the resourceful context of viewsets from DRF. I'd be sharing some helpful insight to harness your use of the DRF. This would be categorised on the following:&lt;br&gt;
&lt;b&gt;i)&lt;/b&gt; Decorators&lt;br&gt;
&lt;b&gt;ii)&lt;/b&gt; custom routes&lt;br&gt;
Let's get on then. &lt;br&gt;
Now, let's take an authentication url for instance, the functionalities you'd definitely want to incorporate, would include, but definitely not exclusive to the following;&lt;br&gt;
a) signup&lt;br&gt;
b) signin&lt;br&gt;
c) forgot password&lt;br&gt;
Personally, I'd include more routes (according to Django's legacy or rules: explicit is better than implicit);&lt;br&gt;
d) OTP &lt;br&gt;
e) user-details &lt;br&gt;
You could have some other you'd like to include, provided they fall under the collective action of authentication and authorizaion.&lt;br&gt;
Now, here comes the question: wouldn't it be cumbersome, that you'd have to write a unique view and then, define a unique url for all these authentication actions? definitely, it would (I don't need to be told).&lt;br&gt;
That's what DRFs' viewsets helps us solve; and as the name implies, "view-sets". You gerrit? Sure you did.&lt;br&gt;
Let's define an API then, using the DRF's viewsets. I'll section the procedures as below;&lt;br&gt;
&lt;b&gt;i) Start a new project&lt;/b&gt; I'll assume you're acquainted with django's best practices about starting a new project i.e creating a virtual environment, defining env files etc. Secondly, the folder structure, for a newly created app in django comes with a views.py file. You can rename that to viewsets.py.&lt;br&gt;
&lt;b&gt;ii) Define the viewset class for users&lt;/b&gt; (say &lt;b&gt;users&lt;/b&gt; is an app on your django project):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from rest_framework import viewsets, status
from .serializers import UsersSerilizer # assuming you've also defined a serializer
from .models import Users # say you've got a users model
from rest_framework.decorators import action
from rest_framework.response import Response

class UsersViewSets(viewsets.ModelViewSet):
    queryset = Users.objects.all() # a queryset variable is mandatory
    serializer_class = UsersSerializer 
    permission_classes = []
    def create(self, request, *args, **kwargs): # ----- for creating a new user
        super().create(request, *args, **kwargs)

    def list(self, request, *args, **kwargs):  # ----- for listing all users
        super().list(request, *args, **kwargs)

    def update(self, request, *args, **kwargs):  # ----- for updating a user
        super().update(request, *args, **kwargs)

    @action(methods=["POST"], detail=False, url_path="forgot-    password")
    def forgot_password(self, *args, **kwargs):
        #... logic
        return Response(data=&amp;lt;whatever data&amp;gt;, status=status.HTTP_201_CREATED, content_type="application/json")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;From the above code, it's obvious that the super keyword is referring to a the methods of a superclass; which implies that you can override those methods as required for your application use case. However, looking at the fourth method, its structure looks different compared to others. Thats a method, defining a custom url: forgot password.&lt;br&gt;
The symbol @, denotes the syntax of a decorator (a function; you can read about decorators in python). This is the procedure for telling DRF that you'd like to define a custom url; because the default methods won't suffice.&lt;br&gt;
The arguments include:&lt;br&gt;
a) methods: what HTTP verb is this url performing?&lt;br&gt;
b) detail: a boolean; tell DRF if this is a detail route i.e if the route construct would require a primary-key, unique email etc, to return a specific instance.&lt;br&gt;
c) url_path: what would you like to call this route?&lt;br&gt;
With the above configuration, you could as well include an otp-verification (just saying) view as well, handle the business logic and return a response (as always). The next step is registering this viewset,so as to be recognised by the app.&lt;br&gt;
&lt;b&gt;iii) Define a router.py file:&lt;/b&gt; this is the file from which we'd register all the viewsets in the app i.e you could have product_viewsets, authentication_viewsets, finance_viewsets etc. You'd register a viewset in like so:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from rest_framework import routers
app_router = routers.DefaultRouter()
# import the viewsets from your various app module
from users import viewsets as users_viewsets
# register your routers as 
app_router.register("auth or whatever you prefer (avoid trailing slashes)", users_viewsets.UsersViewSet, basename="auth")
#... other viewsets registration
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This router.py file must be located in the same directory as the applications urls.py file. &lt;br&gt;
&lt;b&gt;iv) Connect the router.py file to the apps' urls.py file:&lt;/b&gt; finally, in the apps' urls.py file, register the router.py file like so:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from .router import app_router
from django.urls import path, include

urlpatterns = [
    path("your-site/", include(app_router.urls), 
]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;we can therefore refer to our custom route as:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;http://localhost:8000/your-site/auth/forgot-password # for the local server. Don't forget it's https, in production.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Let me know if there are places you find discontinuities. Thanks.&lt;/p&gt;

</description>
      <category>django</category>
      <category>python</category>
      <category>djangorestframework</category>
      <category>backend</category>
    </item>
    <item>
      <title>Finding out the RGB value of an image with python</title>
      <dc:creator>Chukwunazaekpere </dc:creator>
      <pubDate>Mon, 25 Oct 2021 10:16:58 +0000</pubDate>
      <link>https://dev.to/chukwunazaekpere/finding-out-the-rgb-value-of-an-image-with-python-12af</link>
      <guid>https://dev.to/chukwunazaekpere/finding-out-the-rgb-value-of-an-image-with-python-12af</guid>
      <description>&lt;p&gt;As a fulstack developer, challenges comes up in their very unfamiliar forms; hence, the need to be open minded and patient as a developer. I bring you the knowledge of seeking out the RGB or HEX values of an image; using python. So; say for instance, you were working on a mobile app (in my case) and a logo was given to you by the client; and he wants you to use the color codes on the logo as the primary colors for the app; however; without giving you the color codes for any of the colors on the logo. Let's get on then!!!&lt;br&gt;
&lt;b&gt;Step 1: &lt;/b&gt;&lt;b&gt;Create a python script or module&lt;/b&gt;: If you're going to need the functionality of finding out colr codes on images, a python module would be preferable. Otherwise, create a singular script.&lt;br&gt;
&lt;b&gt;Step 2: &lt;/b&gt;&lt;b&gt;Install the PIL library:&lt;/b&gt; install the python manage library. You could create a virtual environment or continue with the working workspace already active. The command below installs the PIL (python image library).&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;pip install pillow
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;b&gt;Step 3: &lt;/b&gt;The code::&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from PIL import Image
import os
filename = os.path.join(os.path.dirname(__file__), "your_image_filename.format")
# ensure that the image exists in your current working path

with Image.open(filename) as rgb_image:
    image_color = rgb_image.getpixel((30,30))
    print(image_color)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The RGB values are displayed; you can then copy to an image picker to get the HEX - values. Thank you!&lt;/p&gt;

</description>
      <category>python</category>
      <category>programming</category>
      <category>images</category>
      <category>pil</category>
    </item>
    <item>
      <title>Project setup for NodeJS-React using Typescript: Running both servers (Express and React) concurrently</title>
      <dc:creator>Chukwunazaekpere </dc:creator>
      <pubDate>Wed, 13 Oct 2021 14:25:37 +0000</pubDate>
      <link>https://dev.to/chukwunazaekpere/project-setup-for-nodejs-react-using-typescript-running-both-servers-express-and-react-concurrently-1cfd</link>
      <guid>https://dev.to/chukwunazaekpere/project-setup-for-nodejs-react-using-typescript-running-both-servers-express-and-react-concurrently-1cfd</guid>
      <description>&lt;p&gt;Developing, whilst seeing the changes update immediately is a feature which eases the programmer of any unplanned certainty as he or she gets to see the effect of each line of code on the frontend and backend. I'll be demonstrating how to setup a MERN project to run both the NodeJS and React servers concurrently. From hereon, I'll be referring to the backend as BE, frontend as FE and database as DB. I'll also be working from a linux environment. Not to worry, whenever ther's a command peculiar to linux, I'll indicate. Additionally, I'll be using yarn (Yet Another Resource Negootiator); you can as well use npm (node package manager). I'll always give the analogical comands for npm as well. Let's get started.&lt;br&gt;
firstly, create a folder; I'll call mine projectOsmium.&lt;br&gt;
&lt;b&gt;a) cd into your project folder and create two folders like so;&lt;/b&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;mkdir {backend,frontend}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;b&gt;b) Acquiring the required files for the FE&lt;/b&gt;: cd into the frontend directory. I'll be working with typescript. Enter the command below to get a project structure with typescript template:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;yarn create react-app &amp;lt;projectName&amp;gt; --template typescript
i.e yarn create react-app osmium --template typescript
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;b&gt;c) Preparing package.json file to run both servers&lt;/b&gt;: cd out of the FE folder; you can simply do:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;cd ..
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now lets get the required resources to run both servers.&lt;br&gt;
&lt;b&gt;i) Make a package.json file to hold our scripts, dependencies etc:&lt;br&gt;
&lt;/b&gt;&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;yarn init -y
or npm init-y
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;The above command will immediately create a package.json file for you. To add a tsconfig.json file, you'd enter:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;tsc --init
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The above command will create a tsconfig.json file for you.&lt;br&gt;
However, the above command can only work, if you've got typescript installed. If you haven't, do:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;yarn add -g typescript
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;b&gt;d) Organising the tsconfig.json file&lt;/b&gt;: &lt;br&gt;
the recommended key-value pair for the tsconfig.json file,is highlighted as below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
  "compilerOptions": {
    /* Visit https://aka.ms/tsconfig.json to read more about this file */

    /* Basic Options */
    // "incremental": true,                         /* Enable incremental compilation */
    "target": "esnext",                                /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', 'ES2021', or 'ESNEXT'. */
    "module": "commonjs",                           /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
    // "lib": [],                                   /* Specify library files to be included in the compilation. */
    // "allowJs": true,                             /* Allow javascript files to be compiled. */
    // "checkJs": true,                             /* Report errors in .js files. */
    // "jsx": "preserve",                           /* Specify JSX code generation: 'preserve', 'react-native', 'react', 'react-jsx' or 'react-jsxdev'. */
    // "declaration": true,                         /* Generates corresponding '.d.ts' file. */
    // "declarationMap": true,                      /* Generates a sourcemap for each corresponding '.d.ts' file. */
    // "sourceMap": true,                           /* Generates corresponding '.map' file. */
    // "outFile": "./",                             /* Concatenate and emit output to single file. */
    "outDir": "./backend/dist",                              /* Redirect output structure to the directory. */
    "rootDir": "./backend/src",                             /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
    // "composite": true,                           /* Enable project compilation */
    // "tsBuildInfoFile": "./",                     /* Specify file to store incremental compilation information */
    // "removeComments": true,                      /* Do not emit comments to output. */
    // "noEmit": true,                              /* Do not emit outputs. */
    // "importHelpers": true,                       /* Import emit helpers from 'tslib'. */
    // "downlevelIteration": true,                  /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
    // "isolatedModules": true,                     /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */

    /* Strict Type-Checking Options */
    "strict": true,                                 /* Enable all strict type-checking options. */
    // "noImplicitAny": true,                       /* Raise error on expressions and declarations with an implied 'any' type. */
    // "strictNullChecks": true,                    /* Enable strict null checks. */
    // "strictFunctionTypes": true,                 /* Enable strict checking of function types. */
    // "strictBindCallApply": true,                 /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
    // "strictPropertyInitialization": true,        /* Enable strict checking of property initialization in classes. */
    // "noImplicitThis": true,                      /* Raise error on 'this' expressions with an implied 'any' type. */
    // "alwaysStrict": true,                        /* Parse in strict mode and emit "use strict" for each source file. */

    /* Additional Checks */
    // "noUnusedLocals": true,                      /* Report errors on unused locals. */
    // "noUnusedParameters": true,                  /* Report errors on unused parameters. */
    // "noImplicitReturns": true,                   /* Report error when not all code paths in function return a value. */
    // "noFallthroughCasesInSwitch": true,          /* Report errors for fallthrough cases in switch statement. */
    // "noUncheckedIndexedAccess": true,            /* Include 'undefined' in index signature results */
    // "noImplicitOverride": true,                  /* Ensure overriding members in derived classes are marked with an 'override' modifier. */
    // "noPropertyAccessFromIndexSignature": true,  /* Require undeclared properties from index signatures to use element accesses. */

    /* Module Resolution Options */
    "moduleResolution": "node",                  /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
    // "baseUrl": "./",                             /* Base directory to resolve non-absolute module names. */
    // "paths": {},                                 /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
    // "rootDirs": [],                              /* List of root folders whose combined content represents the structure of the project at runtime. */
    "typeRoots": ["./backend/src/types", "../node_modules/@types"],                             /* List of folders to include type definitions from. */
    // "types": [],                                 /* Type declaration files to be included in compilation. */
    // "allowSyntheticDefaultImports": true,        /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
    "esModuleInterop": true,                        /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
    // "preserveSymlinks": true,                    /* Do not resolve the real path of symlinks. */
    // "allowUmdGlobalAccess": true,                /* Allow accessing UMD globals from modules. */

    /* Source Map Options */
    // "sourceRoot": "",                            /* Specify the location where debugger should locate TypeScript files instead of source locations. */
    // "mapRoot": "",                               /* Specify the location where debugger should locate map files instead of generated locations. */
    // "inlineSourceMap": true,                     /* Emit a single file with source maps instead of having a separate file. */
    // "inlineSources": true,                       /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */

    /* Experimental Options */
    // "experimentalDecorators": true,              /* Enables experimental support for ES7 decorators. */
    // "emitDecoratorMetadata": true,               /* Enables experimental support for emitting type metadata for decorators. */

    /* Advanced Options */
    "skipLibCheck": true,                           /* Skip type checking of declaration files. */
    "forceConsistentCasingInFileNames": true        /* Disallow inconsistently-cased references to the same file. */
  },
  "exclude": ["../node_modules"],
  "include": ["./backend/src"]

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the tsconfig.json file above, the rootDir and outDir are important. They tell typescript where to get the source codes and store the transpiled javascript files, respectively. Hence, in your BE folder, ensure you have created the src folder. Immediately you run the command "yarn dev", the "dist" folder will be created automatically.&lt;br&gt;
&lt;b&gt;e) Setting-up scripts to run servers&lt;/b&gt;: in your package.json file, create the &lt;b&gt;scripts&lt;/b&gt; object and enter the following:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;.....
"scripts": {
    "client": "yarn start --prefix frontend",
    "server": "nodemon ./backend/dist/index.js",
    "dev": "rm -rf ./backend/dist/index.js &amp;amp;&amp;amp; tsc &amp;amp;&amp;amp; concurrently \"yarn server\" \"yarn client\",
    "start": "node ./backend/dist/index.js"
}
.....
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;b&gt;e) Adding the required devDependencies libraries&lt;/b&gt;:&lt;br&gt;
the required devDependencies libraries can be gotten as shown below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;yarn add nodemon concurrently -D // the -D flag implies that the resources are devDependencies
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You can now run:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;yarn dev
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Connect your DB and other resources.&lt;br&gt;
Thank you for reading!&lt;/p&gt;

</description>
      <category>node</category>
      <category>react</category>
      <category>concurrently</category>
      <category>express</category>
    </item>
    <item>
      <title>Setting-up a Django project for production</title>
      <dc:creator>Chukwunazaekpere </dc:creator>
      <pubDate>Tue, 05 Oct 2021 06:43:24 +0000</pubDate>
      <link>https://dev.to/chukwunazaekpere/setting-up-a-django-project-for-production-543e</link>
      <guid>https://dev.to/chukwunazaekpere/setting-up-a-django-project-for-production-543e</guid>
      <description>&lt;p&gt;Setting up a django project is an expertise worthy of mastery. This is pretty important because; lousiness can be permitted and forgiven, whilst developing locally. However, you would definitely pay dearly, if an attacker should trail your backend-system. This trailing becomes feasible, due to the fact that; confidential variables e.g SECRET_KEY, DATABASE_URL, STATIC_URL, MEDIA_URL or some confidential link etc, required to be kept secret; in a .env file, was mistakenly loosed in the production code. A single link being exposed, can give an idea into several other links or services, to an experienced attacker (cracker). Hence, a proper project setup, is of utmost priority, from the inception of the project. A great advantage to this, is that once setup, it becomes very easy to make reference, from whatever point or line of code in the project. However, this might feel cumbersome, while starting out. Nevertheless, this is unnegotiable as a matter of fact. I'll be working from a Linux environment and hence certain command-line commands will definitely be unique to the platform. You can always lookout for the analogical command specific to your platform. However, these commands will only be used when there are no alternatives. Onward then!&lt;br&gt;
In sequence, let's outline the procedures:&lt;br&gt;
a) &lt;b&gt;Create a folder&lt;/b&gt;; I'll call mine projectTungsten&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;mkdir projectTungsten
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;b) &lt;b&gt;Python version&lt;/b&gt;: for the moment, the most compatible python version recommended (on the basis of the required dependencies; pscopg2, django-heroku etc) for now, is python 3.8. If you've not got python 3.8 installed, get installed.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;for Linux, open a terminal and run: 
a) sudo apt-get update
b) sudo apt-get install python3.8
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If the above doesn't work, get on the AskUbuntu website and ask your question.&lt;br&gt;
c) &lt;b&gt;Setting up a virtual environment&lt;/b&gt;: since we would want to build with python3.8, it implies that our virtual environment must be created using python3.8. Hence, 'cd' (cd: change directory) into your projectTungsten&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;a) cd projectTungsten
b) python3.8 -m venv &amp;lt;environment name&amp;gt;
i.e python3.8 -m venv tungsten_admin
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;d) &lt;b&gt;Activating the virtual environment&lt;/b&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;source tungsten_admin/bin/activate
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If everything has been correctly implemented, the above command shows up on your terminal, with the environment name in parenthesis.&lt;br&gt;
e) &lt;b&gt;Installing the required packages: the foremost packages required includes the following;&lt;br&gt;
&lt;/b&gt;&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;pip install psycopg2 gunicorn django-heroku python-dotenv django django-cors-headers
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;psycopg2: we'll be talking to a postgres database and require a database cursor to help us do so.
gunicorn: a Python WSGI server important, when our application goes live
django-heroku: we'll be pushing the app to heroku servers and this would aid in automatically configuring our Django application to work on Heroku.
python-dotenv: deal with environment variables
django-cors-headers: configure CORS policy
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;f) &lt;b&gt;Configure settings for development and production&lt;/b&gt;:&lt;br&gt;
in your project directory, cd into tungsten_admin; you'll find another folder: tungsten_admin as well. It contains settings.py, urls.py, wsgi.py etc. In this folder, create a new folder: settings. In this settings folder, create three new files:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;touch {base_settings,prod_settings,dev_settings}.py 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;you could as well have renamed your default settings file as base_settings.py.&lt;br&gt;
g) &lt;b&gt;Create a '.env' file &lt;/b&gt;: this file should be cited in the same directory, with the manage.py file. Cut the "SECRET_KEY" in your base_settings.py file and paste in your .env file. This is where every secret detail; database, url, api keys etc should be kept.&lt;br&gt;
h) &lt;b&gt; Create a '.gitignore' file &lt;/b&gt;: this file should be cited in the same directory, with the manage.py file. In this file, add *.env, &lt;strong&gt;pycache&lt;/strong&gt;, *.sqlite3 etc any other file you wouldn't want to commit to the repository.&lt;br&gt;
i) &lt;b&gt;Resourcing manage.py and wsgi.py&lt;/b&gt;: the manage.py file is used locally(in development), while the wsgi.py file, is same with the manage.py, however, is used in production by the server.&lt;br&gt;
in your manage.py file, do:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;"""Django's command-line utility for administrative tasks."""
import os
import sys
import dotenv

def main():
    """Run administrative tasks."""
    dotenv.load_dotenv(
        os.path.join(os.path.dirname(__file__), '.env')
    )

    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'tungsten_admin.settings.dev_settings')

    if os.getenv("DJANGO_SETTINGS_MODULE"):
        os.environ["DJANGO_SETTINGS_MODULE"] = os.getenv("DJANGO_SETTINGS_MODULE")

    # print("\n\t Get env: ", os.getenv("DJANGO_SETTINGS_MODULE"))
    try:
        from django.core.management import execute_from_command_line
    except ImportError as exc:
        raise ImportError(
            "Couldn't import Django. Are you sure it's installed and "
            "available on your PYTHONPATH environment variable? Did you "
            "forget to activate a virtual environment?"
        ) from exc
    execute_from_command_line(sys.argv)


if __name__ == '__main__':
    main()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;in wsgi.py file, do:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import os
import dotenv

from django.core.wsgi import get_wsgi_application

dotenv.load_dotenv(
    os.path.join(os.path.dirname(__file__), '.env')
)

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'tungsten_admin.settings.dev_settings')

if os.getenv("DJANGO_SETTINGS_MODULE"):
    os.environ["DJANGO_SETTINGS_MODULE"] = os.getenv("DJANGO_SETTINGS_MODULE")

application = get_wsgi_application()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;in your .env file, ensure you have defined the variable:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;DJANGO_SETTINGS_MODULE = tungsten_admin.settings.dev_settings
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;j)&lt;b&gt;Assigning variables&lt;/b&gt;: in your dev_settings and prod_settings.py files,you should do&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import * from base_settings
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then, define your development variables e.g database setup, static, media etc in the respective files as you prefer.&lt;/p&gt;

&lt;p&gt;You can spin up your local server: python manage.py runserver&lt;/p&gt;

&lt;p&gt;Like I said earlier,it's a tedious process; however, one that would bring back fruits greater than you could imagine. Let me know your difficulties and I'd be right on time to respond. Thank you.&lt;/p&gt;

</description>
      <category>django</category>
      <category>dotenv</category>
      <category>security</category>
      <category>virtualenv</category>
    </item>
    <item>
      <title>Writing Responsive Components in React</title>
      <dc:creator>Chukwunazaekpere </dc:creator>
      <pubDate>Wed, 22 Sep 2021 09:01:40 +0000</pubDate>
      <link>https://dev.to/chukwunazaekpere/writing-responsive-components-in-react-1cld</link>
      <guid>https://dev.to/chukwunazaekpere/writing-responsive-components-in-react-1cld</guid>
      <description>&lt;p&gt;In this post, we'll get to understand the implementation of certain hooks in react and as well, making a custom-hook. The hooks of concern in this post are; &lt;b&gt;"useEffect", "useRef" and "useState"&lt;/b&gt;. I'll then illustrate, how these hooks can be unified into making a custom hook, for making components responsive. It should be understood that hooks can only be used in functional components. &lt;br&gt;
   Secondly, the name of any react-hook is descriptive; just by "syllabilising" the word into two; &lt;br&gt;
&lt;b&gt;use&lt;/b&gt;: which symbolises that the function is a hook and the other half, e.g &lt;b&gt;Effect, State, Ref, Memo&lt;/b&gt; etc, indicates exactly the action which the hook in question carries out. &lt;br&gt;
   Thirdly, hooks got their rules. Therefore, it is important to first understand these rules, as they apply to all hooks, irrespective of the use-case(s).&lt;br&gt;
Let's get on then, by understanding what the aforementioned hooks do and their place(s) of use.&lt;br&gt;
&lt;b&gt;Effect (useEffect)&lt;/b&gt;: as the name indicates, this hook is basically used to implement an effect: re-rendering of the component, w.r.t the alteration observed in the variable(s) in the dependency array. This implies that; if you'd like for instance, your component to be aware that a new user just registered, so you could render this new user, then there must be a variable, either unique to the component or in the global state (context-API or Redux) that is made aware of this event and hence is kept in dependency array, to trigger a re-render of the component. The general form of usage is like so;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    useEffect(() =&amp;gt; {
      //....call an API or something else
    }, [variable] // the dependency array); 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;b&gt;State (useState)&lt;/b&gt;: regulates the state of a variable in a functional component. Say for instance, I'd like to submit a signup form. Then, I could do the below;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;interface SignupDataInterface {
    firstname: string,
    lastname: string,
    email: string,
    phone: string,
    password: string,
}

   const [signupData, setSignupData] = useState&amp;lt;SignupDataInterface&amp;gt;({
                                          "firstname": "",
                                          "lastname": "",
                                           "email": "",
                                           "phone": "",
                                           "password": "",
                                           })
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The useState hook uses an array "destructuring" feature to provide the variable; signupData and a method to alter the value(s) of this variable. You shouldn't alter the variable-values through any means; but by the use of the method, provided by useState.&lt;br&gt;
&lt;b&gt;Ref (useRef)&lt;/b&gt;: say you would like to keep the value of a variable after a re-render, the useRef is mostly used for this purpose i.e keeping track of the previous value of a variable. It is used like so;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const initialScreenWidth = useRef(window.innerWidth).current;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The above variable holds the initial screen width of a device irrespective of a re-render. Other use case for the useRef-hook exists. Just do the findings!.&lt;br&gt;
&lt;b&gt;Now, lets create our custom-hook&lt;/b&gt;. The reason for this is to implement responsiveness. It then implies that we would want our application to be aware of the devices' dimensions in real time.&lt;br&gt;
Let's write this hook; I called it useWindowDimension (note the first word; "use"):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { useEffect, useState, useRef } from "react";

interface DimensionInterface {
    width: string | number,
    height: string | number
};

const useWindowDimension = () =&amp;gt; {
    // First get the devices dimensions as default value.
    const currentWidth = useRef(window.innerWidth).current;
    const currentHeight = useRef(window.innerHeight).current;

    // This is the effective way of doing it, as opposed to     setting a random value which definitely, isn't true for all devices.
    const [windowDimension, setWindowDimension] = useState&amp;lt;DimensionInterface&amp;gt;({
        width: currentWidth,
        height: currentHeight
    });

// As the devices dimensions change at any time, get the current dimension and set the new dimension as the prevai
    const getDimension = () =&amp;gt; {        
        setWindowDimension({
            width: window.innerWidth,
            height: window.innerHeight
        });
    };
    useEffect(() =&amp;gt; {
        window.addEventListener("resize", e =&amp;gt; getDimension());
        return () =&amp;gt; window.removeEventListener("resize", e =&amp;gt; getDimension());
    }, []);

    return windowDimension;
};


export default useWindowDimension;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, say we would like our p-tags to show headers sizes at varying width, we'd write a component for P-tags;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, {HTMLProps} from 'react'
import useWindowDimension from "../../helpers/useWindowDimension";

interface Props extends HTMLProps&amp;lt;any&amp;gt; {

};

const ParagraphHeaderComponent = (props: Props) =&amp;gt; {
    const { width } = useWindowDimension();

    return (
        &amp;lt;p style={{display: "flex", width: "100%", justifyContent: "center", alignItems: "center", fontSize: width &amp;gt; 500 ? "27px" : "23px", fontFamily: "serif"}}&amp;gt;
            {props.children}
        &amp;lt;/p&amp;gt;
    );
};


export default ParagraphHeaderComponent;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;With this, whenever we're on mobile devices, our application is aware and certainly adjusts the header size.&lt;br&gt;
We could as well hide a sidebar component with this or navbar-links, whilst exposing the hamburger button etc.&lt;/p&gt;

</description>
      <category>react</category>
      <category>responsiveness</category>
      <category>reacthooks</category>
      <category>customhook</category>
    </item>
    <item>
      <title>Environment Variables (i.e hiding variables) in react-native-typescript</title>
      <dc:creator>Chukwunazaekpere </dc:creator>
      <pubDate>Fri, 10 Sep 2021 00:52:13 +0000</pubDate>
      <link>https://dev.to/chukwunazaekpere/environment-variables-i-e-hiding-variables-in-react-native-typescript-528k</link>
      <guid>https://dev.to/chukwunazaekpere/environment-variables-i-e-hiding-variables-in-react-native-typescript-528k</guid>
      <description>&lt;p&gt;With some understanding about ethical-hacking, it should be made obvious, as to how much sensitive information should be guarded, as developers, in our codes. Environment variables are hence, conceptualised, on this basis. In react-native-typescript (typescript basically), the presence of a variable in a code, must be intentionally thought about. This defines the type and consequently, the type of operation permissible on such variable. &lt;br&gt;
In this post, I'll be showing you how to hide a dummy API-key. Onwards then, let's install react-natve-dotenv library, with the command below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;yarn add react-native-dotenv
or npm install react-native-dotenv
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;In our src folder, create a "types" folder. Create a file: "env.d.ts". &lt;br&gt;
In this file, we'd define the variable name as will be used in our code and its type as well:&lt;br&gt;
&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;decalre module "react-native-dotenv" {
    export const API_KEY: string;
    export const REMOTE_BASE_URL: string;
    export const LOCAL_BASE_URL: string;
    .....
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;In our babel.config.js file, we'll add the following&lt;br&gt;
&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;module.exports = {
    presets: [
    'module:metro-react-native-babel-preset', // present by default
  ],
plugins: ["module:react-native-dotenv", {
    moduleName: "react-native-dotenv",
    allowUndefined: false
}]
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;In our tsconfig.json we'll add:&lt;br&gt;
&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
    ...
    "typeRoots": ["./src/types"], 
    ...
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;Then we'll define our variables and values in our ".env" file. Hence, create a ".env" file, this must sit outside your src folder i.e where your package.json file is located. In here define the variables and corresponding values;&lt;br&gt;
&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    API_KEY = something##anything
    ...
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;With all these in place, one last step:&lt;br&gt;
I'd create a config folder in my src folder and then add an env.ts file in the config folder. The reason for this is that; react-native has a "&lt;strong&gt;DEV&lt;/strong&gt;" variable that tells if the app is in production or development mode.&lt;br&gt;
Therefore, in our env.ts file, we'd do the following;&lt;br&gt;
&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import {
    API_KEY,
    REMOTE_BASE_URL,
    LOCAL_BASE_URL
    ...
} from "react-native-dotenv;

const devEnvVariables = {
   API_KEY,
   LOCAL_BASE_URL
}

const prodEnvVariables = {
   API_KEY,
   REMOTE_BASE_URL
}

export interface EnvsInterface {
    API_KEY,
    REMOTE_BASE_URL,
    LOCAL_BASE_URL
}

// If we're in dev use "devEnvVariables" otherwise, use "prodEnvVariables"
export default __DEV__ ? devEnvVariables : prodEnvVariables;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;in our code, say loginScreen.tsx, we'll do the following;&lt;br&gt;
&lt;/p&gt;
&lt;div class="runkit-element"&gt;
  &lt;code&gt;
    
  &lt;/code&gt;
  &lt;code&gt;
    
import envs, { EnvsInterface } from "./config/envs";
const { BASE_URL, API_KEY } = envs;
// as preffered
const handleSubmitForm = async () =&amp;gt; {
    await axios.post(${BASE_URL}/login, {...loginData},       {headers... API_KEY)
}

  &lt;/code&gt;
&lt;/div&gt;



</description>
      <category>reactnative</category>
      <category>typescript</category>
      <category>environmentvariables</category>
    </item>
    <item>
      <title>Uploading images to Cloudinary in react-native-typescript, using react-native-image-picker</title>
      <dc:creator>Chukwunazaekpere </dc:creator>
      <pubDate>Thu, 09 Sep 2021 05:45:09 +0000</pubDate>
      <link>https://dev.to/chukwunazaekpere/uploading-images-to-cloudinary-in-react-native-typescript-using-react-native-image-picker-390l</link>
      <guid>https://dev.to/chukwunazaekpere/uploading-images-to-cloudinary-in-react-native-typescript-using-react-native-image-picker-390l</guid>
      <description>&lt;p&gt;First things first; let's setup a cloudinary account on which we'll be saving our images. If you've not gotten an account with cloudinary, check this out: "&lt;a href="https://cloudinary.com"&gt;https://cloudinary.com&lt;/a&gt;". &lt;br&gt;
Registration is easy! After the registration phase, you'll be directed to your dashboard. On this dashboard, for now, we need information on the following: upload-presets and cloud-name.&lt;br&gt;
Your cloud-name is directly on the top-left corner of your dashboard(once opened). For the upload-preset, do the following:&lt;br&gt;
On the top-right corner of your dashboard, &lt;br&gt;
a) hit the gear icon. &lt;br&gt;
b) Hit on the upload tab. &lt;br&gt;
c) Scroll downwards to the upload preset section. Cloudinary has an upload-preset for you already. All you need do, is; either add a new one or edit what you've got already. It's okay to edit. What we're after, is to change the "signing mode" feature to "unsigned"; which will enable uploads without authentication. However, uploads are restricted if the upload-preset and cloud name aren't provided.&lt;br&gt;
Either ways, ensure that this variables live in your ".env"-file (check out my post on "Environment variables (hiding variables) in react-native). &lt;br&gt;
Codes: &lt;br&gt;
Below is the code to be called upon during an upload:&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;TouchableOpacity onPress={() =&amp;gt; selectFile()} style={styles.packageImageButton}&amp;gt;                                        
                 //...other logic ...
               &amp;lt;/TouchableOpacity&amp;gt;  
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;div class="runkit-element"&gt;
  &lt;code&gt;
    
  &lt;/code&gt;
  &lt;code&gt;
    
const selectFile = async () =&amp;gt; {
        setCloudinaryImage("");
    // Select Image to upload
    // "includeBase64" ensures that images can be converted into forms, readable by cloudinary.
    launchImageLibrary({mediaType: "photo", includeBase64: true, maxHeight: 400, maxWidth: 400}, async e =&amp;gt; {           
    packageDetails["Package Image"] = "";
    const base64Image = e.assets![0].base64;
const base64Img = `data:image/jpg;base64,${base64Image}`;

//======Set the cloudinary details for the package image===
            const uploadedImageData = new FormData();
uploadedImageData.append("upload_preset",CLOUDINARY_UPLOAD_PRESET);
uploadedImageData.append("file", base64Img);
     setPackageDetails({
        ...packageDetails,
        "Package Image": base64Img as string
     });
    setCloudinaryImage(uploadedImageData as any);
//===============================================
        });
const uploadedImage = await axios.post(${CLOUDINARY_BASE_URL}/${CLOUDINARY_CLOUD_NAME}/image/upload/, cloudinaryImage);
packageDetails["Package Image"] = uploadedImage.data.secure_url;
    };

  &lt;/code&gt;
&lt;/div&gt;


</description>
      <category>typescript</category>
      <category>reactnative</category>
      <category>cloudinary</category>
      <category>reactnativeimagepicker</category>
    </item>
  </channel>
</rss>
