<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Refayat Haque on Medium]]></title>
        <description><![CDATA[Stories by Refayat Haque on Medium]]></description>
        <link>https://medium.com/@refayathaque?source=rss-89bc16995c24------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*33GG35samC43kNuTkCUFBw.jpeg</url>
            <title>Stories by Refayat Haque on Medium</title>
            <link>https://medium.com/@refayathaque?source=rss-89bc16995c24------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 17:29:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@refayathaque/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Create your own API in Google Cloud with Terraform]]></title>
            <link>https://medium.com/@refayathaque/create-your-own-api-in-google-cloud-with-terraform-473d7eaeaa6?source=rss-89bc16995c24------2</link>
            <guid isPermaLink="false">https://medium.com/p/473d7eaeaa6</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[terraform]]></category>
            <dc:creator><![CDATA[Refayat Haque]]></dc:creator>
            <pubDate>Fri, 28 Jan 2022 15:50:53 GMT</pubDate>
            <atom:updated>2022-01-28T15:50:53.218Z</atom:updated>
            <content:encoded><![CDATA[<p>All apps, be they web or mobile, have a “backend” they communicate with for users to consume, produce or alter existing data, with the layer <em>in between</em> the app (aka “client”) and the backend being an API (Application Programming Interface).️</p><p>Google Cloud is a cloud provider just like Microsoft Azure and AWS (Amazon Web Services), and you can use those providers to create APIs as well, but we at somtum.io like the Google Cloud implementation. ☁️</p><p>Google Cloud defines an <a href="https://cloud.google.com/api-gateway/docs/about-api-gateway#what_is_an_api">API</a> as, “…an interface that makes it easy for one application to consume capabilities or data from another application. By defining stable, simple, and well-documented entry points, APIs enable developers to easily access and reuse application logic built by other developers.”</p><h3>Why did we feel the need to build an API?</h3><p>In our pursuit to better establish somtum.io, we need to cover all bases of the software landscape. As a true value-provider to small businesses, we cannot limit ourselves to just “frontend”, “backend”, “cloud” or “devops”, we need to do it all. 🌎</p><p>In most bonafide software development teams there are frontend developers coding the client to make <a href="https://restfulapi.net/">RESTful</a> API calls via HTTP to the backend. While frontend developers build the client, backend developers are building out the API for client access to the backend and for the ability to deliver user functionality. Frontend developers only need to know the API endpoints their client needs to hit to perform required functions, these endpoints are published as part of the API by the backend engineers.</p><p>Our goal was to create a simple API prototype to serve as baseline for all future projects. This prototype allows users to interact with Google Cloud Storage, which is a managed service that allows you to store any kind of file in groupings called “buckets”, analogous to AWS’ S3 (Simple Storage Service.) But more specifically, this API lets users create buckets, list buckets, list objects inside buckets, rename objects and delete buckets. In practice, frontend developers can use the published endpoints in their clients to interact with Google Cloud Storage.</p><p>While there are many approaches to API development, we’ve adopted the Google Cloud prescribed methodology, which dictates the use of their API Gateway service and the <a href="https://swagger.io/docs/specification/basic-structure/">Swagger OpenAPI Specification Version 2</a>. This Specification is essentially a YAML file describing the API, and we’ll discuss it further in a dedicated section towards the end. This YAML file will be used by API Gateway to deploy our API. Since this YAML Specification describes our API, the API Gateway, and its associated resources, <strong>cannot be deployed without it</strong>.</p><p>There are several benefits to using <a href="https://cloud.google.com/api-gateway/docs/about-api-gateway#api-gateway">API Gateway</a>, “API Gateway enables you to provide secure access to your services through a well-defined REST API that is consistent across all of your services, regardless of service implementation. A consistent API: Makes it easy for app developers to consume your services and enables you to change the backend service implementation without affecting the public API.”</p><p>As mentioned before, APIs are an integral part of any app development, therefore, we decided to develop this prototype as scaffolding for all our future solutions. The degree of flexibility this methodology brings is immense, for example, we can use this same scaffolding to build APIs acting as intermediaries between IoT (Internet of Things) devices and other backend services, not just web apps running on managed containerization services like Google Cloud Run.</p><p>Having an API implementation of this nature makes it backend <em>agnostic</em>. This exercise sees us deploy a Node.js web app running as a Docker container image in Cloud Run, but if we change our mind and decide to use Serverless Google Cloud Functions as the backend instead we can. All we’ll need to do is change the “backend” argument in the YAML Specification file below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-ngbUJN3k-9iwYYtRIXB3Q.png" /></figure><p>While the general API philosophy allow for full decoupling of concerns between frontend and backend engineers, <em>this</em> methodology takes it even further with decoupling between the API and backend layers. The API Specification author just needs endpoints for whatever service the backend engineers chose to use. We can use different backends for different paths even! For example, if we wanted, we could have the /test path be processed by a <em>different</em> Cloud Run service or a Cloud Function.</p><p>This decoupled characteristic makes us <em>really love</em> this approach. We can separate backend concerns and developers’ assignments accordingly, switch out backends without downtime, and reduce overall complications you would get from a traditional monolithic architecture. The standardization and uniformity achieved with APIs and the OpenAPI Specification result in improved software and software delivery velocity. 🏎️</p><h3>Let’s get ready to rumbleeeeee!!!!!!</h3><p>You need to first <a href="https://console.cloud.google.com/getting-started/checklist">create a Google Cloud account</a>, and in the process you’ll be also be guided in creating a project. Keep the project id handy as we’ll need it for subsequent configuration. Also, you’ll need to set up your local environment for deploying code to, and provisioning infrastructure in, Google Cloud. 💻</p><p>Then you’ll need to install and configure the <a href="https://cloud.google.com/sdk/docs/install">Cloud SDK</a>, it’ll allow you to run gcloud commands from your CLI (Command Line Interface) of choice. Google defines gcloud as, “the <a href="https://cloud.google.com/sdk/gcloud#what_is_the">primary</a> CLI tool to create and manage Google Cloud resources. You can use this tool to perform many common platform tasks either from the command line or in scripts and other automations.” After installing, you’ll have to <a href="https://cloud.google.com/sdk/docs/initializing">initialize</a> and <a href="https://cloud.google.com/sdk/docs/authorizing">authorize</a> it to execute commands on your behalf using your Google Cloud credentials.</p><p>Now that you’ve got gcloud set up, we can move on to Terraform, but prior, we need to understand what Terraform is and how it’s beneficial. “<a href="https://www.terraform.io/">Terraform</a> is an open-source infrastructure as code software tool that provides a consistent CLI workflow to manage hundreds of cloud services. Terraform codifies cloud APIs into declarative configuration files.” You can, “write infrastructure as code using declarative configuration files. HashiCorp Configuration Language (HCL) allows for concise descriptions of resources using blocks, arguments, and expressions.” You can <em>also</em>, “apply changes to hundreds of cloud providers with terraform apply to reach the desired state of the configuration.” ⌨️</p><p>And everything they’re saying sounds great, but again, how’s it beneficial for us? Terraform allows you to, “codify your application infrastructure — Reduce human error and increase automation by provisioning infrastructure as code.” And, “create reproducible infrastructure Provision consistent testing, staging, and production environments with the same configuration.” As a result, you are able to clone our GitHub repository, run the code, and provision <em>identical</em> infrastructure in your own Google Cloud project, this would not be possible without Terraform! 😇</p><p>It’s unfathomable to think about how much more time it would take you to provision infrastructure “by hand” (pointing and clicking around in the Cloud web console). Even worse, you couldn’t replicate your infrastructure in the event of a disaster, or keep track of changes. Infrastructure as code (IaC) is truly the way forward and we at somtum.io are immensely grateful for it. 😌</p><p>With the introduction out of the way, let’s go ahead and get <a href="https://registry.terraform.io/providers/hashicorp/google/latest/docs/guides/getting_started">Terraform set up locally</a>. To ensure that it was set up correctly, we’ll need to initialize (we’ll do this soon), and for that you’ll need the appropriate .tf files. We recommend that you use our code for this exercise, so just clone the <a href="https://github.com/refayathaque/somtum.io-infra-and-images">repository</a> and traverse to the prototype-b directory, this should be your working directory for all Terraform infrastructure provisioning.</p><p>We have all the Terraform files you’ll need except for variables.tf, and the HCL code you need to include in this file can be found <a href="https://github.com/refayathaque/somtum.io-infra-and-images">here</a>. Since the execution of our Terraform code is reliant on these variables, please make sure you double (and triple) check the default strings. You can set the region to wherever you are in the world, and you can find a list of all Google Cloud regions <a href="https://cloud.google.com/docs/geography-and-regions#internal_services">here</a>. project_id and project_number are values you can find on the Google Cloud web console home page.</p><p>You’ll need to create a Google Cloud IAM (Identity and Access Management) Service Account, and its key, for Terraform to have the necessary <a href="https://developers.google.com/workspace/guides/auth-overview#important_terminology">authentication <em>and</em> authorization</a> to provision infrastructure. We’ll discuss IAM and Service Accounts in a little more depth later, for now just know that this is something you need for Terraform to provision in your Google Cloud project. When setting the role for the Service Account make sure you set it to “Editor”, and this will be under “Basic”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UZ7rC6iAYrSjRfoMwCY1Sg.png" /></figure><p>Going back to variables.tf, the fourth variable you need to fill is the pathname of the Service Account key .json file. You can create the key and download it using this <a href="https://cloud.google.com/iam/docs/creating-managing-service-account-keys#creating">guide</a>. <em>For security purposes keep the key in another directory</em> (e.g., ~/Desktop), <strong>you don’t want to accidentally push code with this key!</strong> 👮</p><p>To verify that you configured things correctly you can run terraform init, and if the initializing is successful you’re good to move on to the next steps, in which will be pushing up the container image to Google Cloud. But before doing that we need to go over the main technologies involved in the following phase of our exercise, technologies like Docker, Express.js and Cloud Run. 🤓</p><h3>Docker, Express.js and Cloud Run</h3><p>A Docker “<a href="https://www.docker.com/resources/what-container">container</a> is a standard unit of software that packages up code and all its dependencies so the application runs quickly and reliably from one computing environment to another. A Docker container image is a lightweight, standalone, executable package of software that includes everything needed to run an application: code, runtime, system tools, system libraries and settings.” Docker ensures that the code we write in our local machines will work in the environment Cloud Run is running, exemplifying the spirit of “code anywhere, run anywhere”. 🏄</p><p>Before advancing, let’s also understand what <a href="https://cloud.google.com/run">Cloud Run</a> is. Cloud Run is akin to AWS’ ECS (Elastic Container Service), if you’re more familiar with that. It’s essentially a service that allows you to “develop and deploy highly scalable containerized applications on a fully managed serverless platform”. It’s also highly cost-effective due to it’s “serverless” nature, you “only pay when your code is running.”</p><p>The Docker container image will be running Node.js code leveraging the <a href="https://expressjs.com/">Express.js</a> and <a href="https://github.com/googleapis/nodejs-storage">Google Cloud Storage</a> libraries. Express.js is excellent for creating API backends because it has, “a myriad of HTTP utility methods and middleware at your disposal”. Our Express.js code can be found in the server.js file at nodejs-containers/storage-crud, and upon further examination of both it and the associated Node.js modules, it you’ll see that it’s just a simple web app that responds to HTTP methods by doing some operation on Google Cloud Storage and returning data. Once this container image is deployed to Cloud Run, it’ll become a “<a href="https://www.ibm.com/cloud/learn/microservices">microservice</a>”, and it’s purpose will be to provide the client (the frontend developers’ domain) abilities to interact with Google Cloud Storage and create buckets, delete buckets, delete objects, list buckets, list objects, and change object names.</p><p><em>Before we deploy this Docker container image to Cloud Run</em>, we’ll build and push it to Google Cloud <a href="https://cloud.google.com/artifact-registry">Artifact Registry</a> using Docker, <em>for Cloud Run to later use when it’s being provisioned</em>. And what is Artifact Registry? “Artifact Registry is a single place for your organization to manage container images and language packages (such as Maven and npm). It is fully integrated with Google Cloud’s tooling and runtimes and comes with support for native artifact protocols. This makes it simple to integrate it with your CI/CD tooling to set up automated pipelines.” 🏺</p><p>But more importantly, for now, just understand what this container image is doing, and that’s returning Google Cloud Storage data to the client by leveraging the Express.js and Google Cloud Storage libraries. 📚</p><p>And before proceeding to push the Docker container image to Artifact Registry, we want to communicate our intention with this code, which is for others to take and tweak as necessary. To maybe have a Node.js web app that interacts with <em>other</em> Google Cloud services or even other Cloud provider’s services. If you want, for example, to create a web app that interacts with Google Cloud’s Machine Learning service you just have to incorporate the AutoML Node.js <a href="https://github.com/googleapis/nodejs-automl">library</a> and change the code accordingly.</p><p>In deploying this API we’ll be taking a two-step approach to infrastructure building, and that is due to the way Cloud Run services work. As mentioned above, since Cloud Run needs to know what container image to use we must first build and push the container image.</p><h3>Infrastructure provisioning part un</h3><p>To make everyone’s lives easier, we wrote a bash script aptly named run-me-first.sh, and it does three things. <em>First it enables the Google Cloud service api for Artifact Registry</em> resources to be created using Terraform, without enabling this api we won’t be able to create the repository the Docker container image will be pushed into. Second, it uses Terraform again to <em>create</em> the aforementioned repository.</p><p>It’s important to note that this bash script will use Terraform to <strong>only enable the Artifact Registry api and provision the the repository</strong>.<strong> </strong>Why do we care? It’s because Terraform themselves <em>frown upon this practice of using </em>terraform apply -target<em> to provision </em><strong><em>select</em></strong><em> resources</em>, but until we can find a better solution for having Docker container images be available for Cloud Run <em>before creating the Cloud Run service</em>, this is all we can do. 🤷‍♂️</p><p>In keeping with Google Cloud service apis, you’ll see that we have an apis.tf file, and that includes Terraform resource representations of these Google Cloud provider <em>api enablements</em>. As discussed above, we need to enable certain Google Cloud service apis for infrastructure provisioning, otherwise Terraform will throw errors. We’ve written all the Terraform code in a way where the provisioning of a resource <em>will only occur if its respective Google Cloud service api has been enabled</em> (this is what the depends_on argument is doing in our .tf files).</p><p>Third, this script will <a href="https://cloud.google.com/build/docs/building/build-containers#store-images">build and push the Docker container image to Artifact Registry</a>. However, you’ll have to <strong>change the variables before you can run this script</strong>. Your region and project id will differ, and if you clone or fork our GitHub repository then you can keep the ARTIFACT_REGISTRY_REPO_NAME and IMAGE_NAME as they are.</p><p>Run this script with bash run-me-first.sh and watch the magic unfold. ✨</p><p>Assuming all commands were executed successfully, you’ll have provisioned the Artifact Registry repository and pushed the Docker container image into it.</p><p>So are we are <em>now</em> ready to provision all remaining infrastructure? Especially the Cloud Run service which needed the container image to be available from Artifact Registry? Not quite, before moving to phase two, we need to go into the Google Cloud web console and enable the app that links Google Cloud to GitHub for <a href="https://www.redhat.com/en/topics/devops/what-is-continuous-delivery">Continuous Delivery</a> with Cloud Build. Terraform will not be able to provision the Cloud Build resource without you having done this first, and don’t worry we’ll explain what Cloud Build does in the next section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TMN_gLIicgA5AO-aR5_a1A.png" /></figure><h3>Infrastructure provisioning part deux</h3><p>Sorry for the tease (again), but before <em>actually</em> provisioning the rest of our infrastructure, we want to talk a little about the Terraform code you see and the Google Cloud services they represent. We won’t go into too much detail describing the Terraform code, as it’s all quite understandable from the <a href="https://registry.terraform.io/providers/hashicorp/google/latest/docs">documentation</a>, however, it would be remiss of us if we didn’t mention that the documentation is <em>not the best.</em> It’s apparent that Hashicorp (the creators of Terraform) decided to allocate more of their engineering prowess on AWS and Azure. In their defense this is to be expected given that <a href="https://financesonline.com/cloud-computing-statistics/">Google Cloud only commands 8% of the market</a>, compared to 32% for AWS and 18% for Microsoft Azure. 😐</p><p>In this section, we’ll briefly touch upon each of the .tf files you see starting with api_gateway.tf and ending with storage.tf.</p><p>The api_gateway.tf file is provisioning Google Cloud’s API Gateway service, its gateway and its config. While the the API itself serves as the parent component, the gateway and the config sit within it as child components. <em>You need all three of these components for the API implementation to work</em>.</p><p>“Using <a href="https://cloud.google.com/api-gateway/docs/about-api-gateway#api-gateway">API Gateway</a>, app developers consume your REST APIs to implement apps. Because all APIs are hosted on API Gateway, app developers see a consistent interface across all backend services. By deploying your APIs on API Gateway, you can update the backend service, or even move the service from one architecture to another, without having to change the API. As long as the API to your service stays consistent, app developers will not have to modify deployed apps because of underlying changes on your backend.”</p><p>As mentioned above, “an API defined on API Gateway consists of <a href="https://cloud.google.com/api-gateway/docs/deployment-model">two main components</a>:</p><ul><li>API config: The API configuration created when you upload an API definition. You create the API definition as an OpenAPI spec. If your API manages gRPC services on Cloud Run, you can define your API with a gRPC service definition and configuration. Each time you upload an API definition, API Gateway creates a new API config. That is, you can create an API config <strong>but you cannot later modify it</strong>. If you later edit the API definition in the OpenAPI spec or gRPC service definition, and then upload the edited API definition, you create a new API config.</li><li>Gateway: An Envoy-based, high-performance, scalable proxy that hosts the deployed API config. Deploying an API config to a gateway creates the external facing URL that your API clients use to access the API.”</li></ul><p>If everything has been set up correctly, Terraform, at the end of provisioning all our infrastructure, will output the API Gateway default hostname URL. This will be the base URL for our API endpoints, and we’ll use this to test out the API and all its functionalities later on. 🤩</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P3rgrYrTDQQjx8bFUGKktQ.png" /></figure><p>The cloud_build.tf file is provisioning our Continuous Delivery pipeline in the form of a <a href="https://cloud.google.com/build/docs/automating-builds/create-manage-triggers">Cloud Build trigger</a>. We are using Cloud Build to deploy the latest version of the Docker container image every time we update the container image source code in GitHub. And we must reemphasize how important it is for you to <em>enable the Github app in the Google Cloud console first</em>.</p><p>Cloud Build relies on a <a href="https://cloud.google.com/build/docs/build-config-file-schema">build config file</a> delineating the build steps, and looking at this file (cloudbuild.yaml) you’ll see that we’re <a href="https://cloud.google.com/build/docs/building/build-containers#store-images">building the container image, and pushing it to Artifact Registry</a>, with Docker and then <a href="https://cloud.google.com/build/docs/quickstart-deploy">deploying it to Cloud Run</a> using gcloud. Please also pay close attention to the filename and included_files arguments in the file, <em>based on how you structure your project, these paths could be different</em>.</p><p>The cloud_run.tf file is provisioning the Cloud Run service, and what’s salient here is the containers block where we declare what Docker container image should be used in creating this microservice.</p><p>iam.tf is provisioning Google Cloud Identity Access Management (IAM) resources. IAM resources grant our provisioned resources with the <em>authorization required to interact with each other and </em><strong><em>allow us to access them</em></strong>. IAM is very nuanced and we, <em>Cloud and DevOps engineers, have to maintain a very strong grasp of it as security is always paramount.</em> But for the purposes of this exercise, the rudimentary explanation above will suffice, if you’d like to learn more you can check out the IAM <a href="https://cloud.google.com/iam/docs/overview">documentation</a>.</p><p>The three main components of IAM are <strong>Principal, Role and Policy</strong>, and for you to comprehend what’s in our code, definitions for each are below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rUgdplLFbk4BvHnYrcyHmg.png" /></figure><p>“A principal can be a Google Account (for end users), a <a href="https://cloud.google.com/iam/docs/service-accounts#what_are_service_accounts">service account</a> (for applications and compute workloads), a Google group, or a Google Workspace account or Cloud Identity domain that can access a resource. The identity of a principal is an email address associated with a user, service account, or Google group; or a domain name associated with a Google Workspace account or a Cloud Identity domain.”</p><p>“A role is a collection of permissions. Permissions determine what operations are allowed on a resource. When you grant a role to a principal, you grant all the permissions that the role contains.”</p><p>“The IAM policy is a collection of role bindings that bind one or more principals to individual roles. When you want to define who (principal) has what type of access (role) on a resource, you create a policy and attach it to the resource.”</p><p>If you’re interested in learning more about how we created our roles, you can take a 👀 at the iam.tf code and look for Terraform resource types google_project_iam_custom_role. You’ll notice that in the permissions argument we have an array with specific Google Cloud IAM permissions, and the reason we did this is to adhere to the Cloud agnostic “Principle of Least Privilege”.</p><p>Google Cloud <a href="https://cloud.google.com/blog/products/application-development/least-privilege-for-cloud-functions-using-cloud-iam">documentation</a> explains this security practice, “the principle of least privilege states that a resource should only have access to the exact resource(s) it needs in order to function. For example, if a service is performing an automated database backup, the service should be restricted to read-only permissions on exactly one database. Similarly, if a service is only responsible for encrypting data, it should not have permissions for decrypting data. Providing too few permissions prohibits the service from completing its task, but providing too many permissions can have rippling security ramifications.”</p><p>Using this philosophy, we made sure that the IAM Custom Role bound to the Cloud Run microservice (through its Service Account) will have limited permissions, <strong>permissions to only execute the Google Cloud Storage operations its designed for, and nothing more</strong>.</p><p>Finally, storage.tf is provisioning three buckets for the purposes of testing at the end of our exercise, and only one of these buckets will have an object inside, with the object being a test.txt file.</p><p>Now that we have some understanding of what the Terraform code is doing, let’s dig a little further into OpenAPI and API Gateway. “An <a href="https://cloud.google.com/api-gateway/docs/openapi-overview#basic_structure_of_an_openapi_document">OpenAPI document</a> describes the surface of your REST API, and defines information such as: The name and description of the API, The individual endpoints (paths) in the API, How the callers are authenticated”.</p><p>“<a href="https://cloud.google.com/api-gateway/docs/openapi-overview">API Gateway</a> supports APIs that are described using the OpenAPI specification, version 2.0. Your API can be implemented using any publicly available REST framework… You describe your API in a YAML file referred to as an OpenAPI document… One of the primary benefits to using OpenAPI is for documentation; once you have an OpenAPI document that describes your API, it is easy to generate reference documentation for your API. There are other benefits to using OpenAPI. For example, you can: Generate client libraries in dozens of languages…” ⛩️</p><p>In the api-configs directory you’ll find the Specification file we’re using to deploy API Gateway, and upon opening it you’ll see that we wrote this YAML file based on guidance from the API Gateway and <a href="https://swagger.io/docs/specification/2-0/basic-structure/">OpenAPI</a> documentation.</p><p>Our YAML file also matches how we’ve set up the Express.js routes in the container image source <a href="https://github.com/refayathaque/somtum.io-infra-and-images/blob/main/nodejs-containers/storage-crud/server.js">code</a> (in server.js). For example, the GET method to fetch all objects in a bucket is described by the path /objects/{bucket} with the parameter being {bucket}, and it’s the similar (syntax differs as one is YAML and the other JavaScript) in server.js, app.get(“/objects/:bucket”, async (req, res) =&gt; {.</p><h3>Almost done!</h3><p>Now that we’ve gone over the code and the main concepts, we can (finally! 😠) provision the second group of infrastructure. Once again, please ensure that you have the <em>Github app integrated with Cloud Build</em>.</p><p>Run terraform apply — auto-approve and watch your infrastructure get built in your Google Cloud project! 🎉</p><p>However, it must be said that, Terraform <strong>could</strong> throw some errors in relation to API Gateway. But if you just try and re-provision everything (terraform apply — auto-approve again) it should be successful the second time around, and you’ll see these two outputs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P3rgrYrTDQQjx8bFUGKktQ.png" /></figure><h3>Testing</h3><p>To test that our API is working as expected we’ll take the API Gateway default hostname returned by Terraform (see above) and append routes described in the OpenApi Specification file, inserting parameters wherever necessary. We’ll be using the curl command to make requests to our backend using GET, POST and PUT methods, the command samples below should help you craft URLs.</p><p>Since we used a random string generator to name the three test buckets (look at storage.tf) you should go to the web console and note the name of the bucket that has the test.txt object, you’ll need to know this when testing the <em>fetch objects</em> functionality.</p><p>Also, before you start testing, you’ll need to <a href="https://cloud.google.com/docs/authentication/api-keys#creating_an_api_key">get an API key</a> from the web console, this API key is passed in as a query string, and it authorizes the endpoints to access your Google Cloud resources. To uphold security best practices, make sure to delete this API key once you’re done testing, you can always create new ones. 🛡️</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_TpJ7O22kJJ2iBMloHUUww.png" /></figure><p>Your default hostname will look something like this <a href="https://storage-crud-gw-xxxxxxxx.uk.gateway.dev/">https://storage-crud-gw-xxxxxxxx.uk.gateway.dev</a> Create your testing curl commands by appending to the default hostname, following our examples below:</p><p>curl {api_gateway_default_hostname}/buckets?key={API_key}</p><p>curl {api_gateway_default_hostname}/objects/{bucket_name}?key={API_key}</p><p>curl -X POST {api_gateway_default_hostname}/buckets/{bucket_name}?key={API_key}</p><p>curl -X DELETE {api_gateway_default_hostname}/buckets/{bucket_name}?key={API_key}</p><p>curl -X DELETE {api_gateway_default_hostname}/objects/{bucket_name}/{object_name}?key={API_key}</p><p>curl -X PUT {api_gateway_default_hostname}/objects/{bucket_name}/{object_name}/{new_object_name}?key={API_key}</p><p>Our code is set up so you get error messages if something didn’t work, but if you’re still curious to see if things <em>really</em> worked, you can hit the first two endpoints (list buckets and objects) and check what’s in Google Cloud Storage. 🪣</p><h3>Conclusion</h3><p>Congratulations on setting up your own API!</p><p>While we encourage celebrating 🍾, we want you and your environments to be protected, so remember to destroy the API key you used for testing. We also advise tearing down your entire infrastructure by running terraform destroy --auto-approve, this way, you not only prevent malicious actors from potentially accessing your infrastructure, but you also eliminate the likelihood of incurring unexpected cloud charges. 💰</p><p>Furthermore, it would be careless of us not to mention that the ideal scenario for Cloud Run security would be to <em>block direct access to the microservice</em>. Since we’re accessing it via API Gateway endpoints we don’t need to expose the Cloud Run service publicly on it’s own. Due to time constraints we were unable to look into this, but if you have any thoughts please let us know and we can update this guide. 🙏</p><p>In closing, we really hope this is helpful in any projects you embark upon, and if something is incorrect or insufficiently explained please reach out, we’ll be more than happy to engage. At somtum.io we firmly trust in learning by doing, and <strong>more importantly, learning from others</strong>. Thank you for giving us your time and have a great rest of your day. 🤗</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=473d7eaeaa6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[This pandemic will create a better you]]></title>
            <link>https://medium.com/@refayathaque/this-pandemic-will-create-a-better-you-36746073669a?source=rss-89bc16995c24------2</link>
            <guid isPermaLink="false">https://medium.com/p/36746073669a</guid>
            <category><![CDATA[discovery]]></category>
            <category><![CDATA[empathy]]></category>
            <category><![CDATA[self-love]]></category>
            <category><![CDATA[self-improvement]]></category>
            <category><![CDATA[discipline]]></category>
            <dc:creator><![CDATA[Refayat Haque]]></dc:creator>
            <pubDate>Wed, 07 Oct 2020 01:03:15 GMT</pubDate>
            <atom:updated>2020-10-07T01:03:15.930Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2NdYHJKtrfcGFbF8" /><figcaption>Photo by <a href="https://unsplash.com/@timmossholder?utm_source=medium&amp;utm_medium=referral">Tim Mossholder</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>There’s no qualm over the fact that we’re all experiencing something truly unprecedented and challenging. As a society, we’ve never encountered something like this, and it’s safe to assume that up to three generations prior haven’t either.</p><p>While society is slowly becoming more benign, large parts still give veracity to the notion that expressing discomfort, suffering, pain, and trepidation is a sign of ‘weakness’, or worse, it’s associated with ‘femininity’. This baseless and misogynistic judgment still permeates much of the developing world, where some of us originate from. It’s a sad reality, but especially during this tumultuous period, we must consciously discount it and instead engage in its antithesis.</p><p>Discussions around topics of self-care, counseling, and ‘speaking your mind’ are essential as we navigate through the pandemic.</p><p>Our lives have been upended in the last couple of months, and we need to grieve. Despite the importance of grieving, it’s paramount that we don’t grieve for too long. We need to allow the natural state of grief to complete its journey, then immediately critique it and pick ourselves back up again.</p><p>What do I mean by this? While it’s ill-advised to disregard the ache we’re all feeling, what we ought to focus more on is taking stock of the current situation, and the negativity embedded in society, and then countering the pessimism and improving our lives and of those around us.</p><p>The pandemic has made it evident that there are countless things that are beyond our control, and that shocks of this nature could repeat themselves and therefore should not go unprocessed. We need to internalize this and be able to combat the adverse impact from the future, largely inevitable, shocks. A change in mentality and our daily-routine is in order if we are to come out of this unscathed and better-prepared for what could be next.</p><p>The two concepts we all need to galvanize around in order to rise up much stronger are <em>resiliency</em> and <em>humility</em>. Building on, and practicing, these concepts has helped me tremendously these past few months, and I’m confident they will help you as well.</p><p>Resiliency simply suggests having the emotional resolve to withstand shocks, be they a natural one like CoViD-19 or something else like the loss of a livelihood or loved one. And there are several ways to build this ‘resiliency’ I speak of, and often times it involves building faith and trust in a positive outcome and learning how to <em>maintain</em> that faith and trust.</p><p>You can do things to be more optimistic, but you must <em>consistently</em> execute on those things to <em>stay</em> optimistic. Optimism is a simple way to achieve resiliency and one way I have been able to remain optimistic is by journaling. Journaling is crucial in <em>sustaining</em> my optimism. Once I devised my recipe for attaining and holding on to, optimism, happiness, and contentment, I began to repeat it to myself on a daily basis through journaling.</p><p>Some folks could urge one to ‘free-journal’ instead, i.e., write down any negative or positive thoughts entering the mind, be they external matters permeating in or something introspective. Free-journaling basically asks someone to put to paper anything causing distress or provoking thought at that specific time. Although this approach has its merits, what works even better is regurgitating a ‘pre-conceived body of words’.</p><p>This pre-conceived body of words took me several months to draft, and in effect, is superior in re-affirming my commitments to living a better life. As I was living through the ebbs and flows of the pandemic, I wrote down what made me happy and upset, what I consider important, and what I want out of my life. Based on my responses I now have the body of words I write over and over again every morning.</p><p>It would be remiss of me to try and influence what could be your own body of words for journaling, as it’s something deeply personal derived from the soul. However, to help you start the process, I’ll outline a few things I have in my body of words and that has been crucial in improving my emotional state.</p><p>First and foremost, you must remind yourself continuously that you are much better off than most others, and this is an example of the concept of <em>humility</em> I mentioned above. It’s absolutely imperative that we remain grounded, as we are susceptible to being consumed by the toxicity of mainstream news and social media, whose purpose at times is to stoke fear and anguish. Only reminding ourselves of all that’s good in the world, and in our lives, can we uphold a positive mindset, so continuously remind yourself to stay down-to-earth and grateful. Recognizing the struggles of folks that are less fortunate will provide perspective and allow you to better value what you have. Frequently ruminate about your health, family, and the fact that you have a job and a roof over your head.</p><p>Second, remind yourself that you ought to be kind and considerate to others. It’s a well-known axiom that you will feel better about your life if you treat others well. I know it’s not possible to physically see our friends and family as frequently as we did in the past, but doing something simple like texting them to say that you love and value them is enough. Doing something nice for others will instantly lift your spirits when you’re feeling down.</p><p>Lastly, consider reducing (or even better, eliminating) social media intake. Recurring studies show how social media is deleterious and leads to inexorable, and often unnoticeable, rise in depression and anxiety. By reminding myself of the afflictions brought about by social media I have successfully weaned off all popular platforms, and I feel much happier and more in control of my life and destiny. (Watch <em>The Social Dilemma</em> on Netflix)</p><p>These are some of the things I included in my journal to remind myself on a daily basis of the path to resiliency and humility I have chosen for myself.</p><p>Other ways to build resiliency and address grief are through meditation and exercise.</p><p>Exercising, in particular, can be a chore to some, so try and get it done first thing in the morning, that way you can focus on other things during the day. Exercising is known to boost serotonin and dopamine levels in your body, assuaging stress and anxiety. As a matter of fact, not only is my morale heightened throughout the day as a result of an exercise in the morning, but I find it to give me a better form of energy than any caffeine product.</p><p>Meditation is newfound for me, and I embraced it through the ‘Calm’ app. I’ve been doing its 10-minute guided meditations twice a day, and have felt more in control of my life and my emotions. It’s the breathing exercise and introspective journey that help to regulate your body’s tempo and calm you down. I highly suggest you try it out, if not twice a day then at least once a day.</p><p>There are many prescriptions here but I implore you to do your own research into how others are dealing with this difficult period in their lives, and if you have any questions please feel free to reach out.</p><p>Making sure that we are living healthy and positive lives in the midst of the crisis will not be easy, and will necessitate proactivity and discipline in making substantial changes to your life in the form of new habits. Only through repetition and consistency will you be able to mold yourself into the person you want to be.</p><p>But also be empathetic to yourself, you won’t always meet your goals and your feelings of sadness and hurt could return, and that’s okay. Over time, as you <em>strive</em> to consistently work on your habits, you’ll start to see a better you. We’ll all get through this, just remember that <em>resiliency</em> and <em>humility</em> will be instrumental.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=36746073669a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Refactor React-Redux with Hooks]]></title>
            <link>https://medium.com/@refayathaque/refactor-react-redux-with-hooks-45d154e444a5?source=rss-89bc16995c24------2</link>
            <guid isPermaLink="false">https://medium.com/p/45d154e444a5</guid>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[redux-thunk]]></category>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-hook]]></category>
            <dc:creator><![CDATA[Refayat Haque]]></dc:creator>
            <pubDate>Tue, 01 Sep 2020 20:49:30 GMT</pubDate>
            <atom:updated>2020-09-01T20:49:30.682Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HO9spoCMFW3Evafc" /><figcaption>Photo by <a href="https://unsplash.com/@sunlifter?utm_source=medium&amp;utm_medium=referral">Tomasz Frankowski</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Don’t get me wrong, I adore Redux and its implementation with React. Once I subdued the state management library and its associated design patterns, I leveraged it for countless projects. Despite there being “too much abstraction” and having to “jump between different files” it actually grew quite intuitive to me. <a href="https://reactjs.org/docs/hooks-intro.html#complex-components-become-hard-to-understand"><em>1</em></a> I knew the flow of setting up action creators, reducers, store, component subscriptions with mapStateToProps, etc., like the back of my hand. And I didn’t mind it, to the point where I got a little burst of dopamine every time I had an epiphany discovered a need for an additional global state object. <a href="https://www.webmd.com/mental-health/what-is-dopamine#1"><em>2</em></a> “Yes!”, I exclaimed, “I get to create more files and hook (no pun intended?) everything up to create another global state object!”. In hindsight, my elation to this was quite bizarre.</p><p>However, part of me knew that this practice wasn’t sustainable, especially as I started encountering increasing amounts of literature on “Hooks” and how it could <em>potentially</em> supplant Redux. The growth-minded Refayat began to pay an inexorable amount of attention to this React 16.8 development, but the desire to start learning Hooks, <em>and</em> transition, fully manifested itself and came to fruition when I recently started a new job. With a change of development stack at work, a change in my personal stack felt natural, matter-of-fact, and necessary.</p><p>Another facilitator of this pursuit to understand Hooks was the realization of how inextricably linked Hooks are to performance gains. I mean, it makes sense, why not utilize an in-built React offering for global state management? Removing Redux will only pay dividends down the road as you start to include more mission-critical node packages. Having ruminated on improving React performance and clamoring to myself to find the time to start learning Hooks for long enough, I finally began, and it wasn’t as easy as I perceived.</p><p>The Redux architecture and design pattern, while beneficial in comprehending Hooks, also impedes the learning effort as it’s (yes, even at the time of writing) so deeply ingrained in my mind. Unconsciously comparing what I was learning back to Redux and allowing my habit-driven biases guide my thought were hindrances. There <em>are</em> a lot of similarities to take advantage of, but the differences could trip you up and regress your grasp over Hooks-specific concepts.</p><p>Therefore, I will be as scrupulous as I can be in explaining how to build yourself a simple Hooks-based React application that can perform asynchronous fetch operations and disseminate the retrieved data to multiple components. Additionally, we’ll share the fetched data amongst components within a nested hierarchy of both siblings and children, in order to better demonstrate the extent to which Hooks can be utilized in lieu of Redux.</p><p>I will be drawing parallels to Redux for easier (hopefully) comprehension of this new (and somewhat esoteric) React development. My assumptions are that you possess familiarity with React, React-Redux, Redux-Thunk, interchangeability and interoperability between class and functional components, and ES6 tools like object and array de-structuring. This tutorial’s reliance on purely functional components stems from the official documentation which says that, “Hooks let you use more of React’s features without classes”, and it goes on to say that, “…components have always been closer to functions. Hooks embrace functions…” <a href="https://reactjs.org/docs/hooks-intro.html#classes-confuse-both-people-and-machines"><em>3</em></a> If this sounds cryptic to you, you’re not alone, but our subsequent deep dives into the myriad of different Hooks will shed more light and make it clear why functional components are better suited.</p><p>The API we’ll be using in this exercise is the ubiquitous <a href="http://jsonplaceholder.typicode.com/">JSONPlaceholder</a>, from which we’ll fetch and create posts.</p><p>All you’ll need to get started is a new React project with <a href="https://reactjs.org/docs/create-a-new-react-app.html#create-react-app">Create React App</a>, and this project doesn’t have any node package dependencies.</p><p>Provided below is how our application will look upon initial render, I’ve used borders to clearly delineate component boundaries, with <em>dotted</em> borders representing “Providers” (more on this later). In essence, we’ll be taking user input, fetching data with it, then disseminating the data to components rendering the fetched data (surrounded by solid borders).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qMlMQ_bimtcb0uLhkfAPYA.png" /></figure><p>The codebase is available <a href="https://github.com/refayathaque/intro-to-hooks/tree/master/src">here</a>, and I will reference by filename/component as we build this out.</p><p>Let’s begin by creating our &lt;Input /&gt; component, whose purpose will be to capture a user selection from a hard-coded dropdown with integer values. Once the user makes their selection we’ll fetch the data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ff418ea786dc87410f2acf77a8daa8da/href">https://medium.com/media/ff418ea786dc87410f2acf77a8daa8da/href</a></iframe><p>As you can see above, while we are capturing user input, we are not fetching in this component, instead, we are relying on “custom” Hooks by the name of useFetchPosts and useFetchComments to do the fetching. A custom Hook is nothing but a function, but the reason why it’s isolated away from the component is for it to be reusable, i.e., another component can also use the same custom Hook to fetch data. It’s defined as “a mechanism to reuse <em>stateful logic</em>… every time you use a custom Hook, all state and effects inside of it are fully isolated.” <a href="https://reactjs.org/docs/hooks-custom.html#using-a-custom-hook"><em>4</em></a></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e2abdf814713739692ff190e21ef91eb/href">https://medium.com/media/e2abdf814713739692ff190e21ef91eb/href</a></iframe><p>From the import statement at the top it’s clear that we’ll be using three in-built React Hooks in this custom Hook, so let’s go through them one by one and see how they work.</p><p>First, we have useState, which is used to manage local state, serving the same purpose as this.state and setState in class-based components. useState, “returns a stateful value, and a function to update it.” setState “function is used to update the state. It accepts a new state value and enqueues a re-render of the component. If the new state is computed using the previous state, you can pass a function to setState. The function will receive the previous value, and return an updated value.” <a href="https://reactjs.org/docs/hooks-reference.html#usestate"><em>5</em></a> The value passed into the useState function will be the initial state. Since useState returns in the form of an array (index determines reference) you can refer to state and setState as whatever you’d like. In our case, we’ll reference the two array values asuserId and setUserId. So where are these array values being used?</p><p>The setUserId function is returned by this custom Hook for any component to take and use as a callback to pass in the userId. In our case, &lt;Input /&gt;uses this callback (see line 6, setUserIdPosts) to pass the user’s selection. So at this point, we understand what useState does and how it’s setting state locally in the custom Hook, and now we’ll look at useEffect and understand how it <em>uses</em> <em>this local state</em>.</p><p>useEffect serves similar purposes to lifecycle methods in class-based components. useEffect takes a function, and the function “will run after the render is committed to the screen.” This Hook’s key merit lies in the fact that “by default, effects run after every completed render, but you can choose to fire them only when certain values have changed. An effect is always recreated if one of its dependencies change”, and we can provide dependencies by passing a “second argument to useEffect that is the array of values that the effect depends on”. Interestingly, “if you pass an empty array, the props and state inside the effect will always have their initial values”, resulting in similar behavior to componentDidMount. <a href="https://reactjs.org/docs/hooks-reference.html#useeffect"><em>6</em></a></p><p>Therefore, it’s safe to assume that this in-built Hook essentially supplants the lifecycle methods componentDidMount and componentDidUpdate. We are relying on useEffect to make our fetches more efficient by using its “dependencies” as mentioned above. To ensure that our application isn’t making incessant fetches to the API, we should only fetch new data when the user input changes, so we need a way for the fetch to “watch” for changes in user input. We have access to the user input through the local state userId, and if we pass that in as a dependency to the useEffect Hook we are only invoking the useEffect block whenever the userId changes, emulating the lifecycle method componentDidUpdate.</p><p>However, you must be wondering why our fetching logic isn’t directly declared in the useEffect block, it’s encapsulated in the fetchData function, and the function is called within the block. There is a specific reason for this and it has to do with the async/await syntax, and this is a notable useEffect caveat worth grasping.</p><p>The Hook will only return a cleanup function or nothing at all, and this presents a challenge because functions annotated with async return an implicit promise, and by definition of useEffect we cannot have anything being returned. So the workaround comes in the form of defining the async annotated function first, then calling it inside the useEffect block, rather than using the async function directly. <a href="https://www.robinwieruch.de/react-hooks-fetch-data"><em>7</em></a></p><p>Ok, that explains the roles useState and useEffect play, one captures the user’s selection and the other carries out the data fetch based on whether or not the user selection has changed. But what about useContext, what’s it for? Before we try and comprehend this third in-built Hook, we have to examine the Context itself.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/be0fe7d5ad0f241a72e6567ae6b259df/href">https://medium.com/media/be0fe7d5ad0f241a72e6567ae6b259df/href</a></iframe><p>From the outset, this Context is looking <em>a lot</em> like a Redux/Redux-Thunk pattern reducer, we even see the word “reducer” being used, which is good, we are now seeing parallels with Redux. This Context can be thought of as analogous to a Redux reducer, while the custom Hook we were looking at earlier analogous to a Redux action creator. But what exactly is a “Context”?</p><p>Context was designed to circumvent “props-drilling”, a phenomenon Robin Wieruch describes as, “clutters every component in between which has to pass down these props without using them”. Redux also addresses this problem and provides a solution for it, but we’re not using Redux! :|</p><p>Wieruch goes on to explain that, “..Context gives you a way out of this mess. Instead of passing down the props down through each component, you can <em>tunnel</em> props through these components implicitly with React Context. If a component needs access to the information from the context, it can <em>consume</em> it on-demand, because a top-level component <em>provides</em> this information in the context.” <a href="https://www.robinwieruch.de/react-context"><em>8</em></a> Yup, it’s principally Redux’s main value proposition, but this parallel is a positive because it’ll make it easier to understand and migrate over :)</p><p>Let’s explore this file above line by line, and scrupulously, to see what’s going on. First of all, we need to comprehend what createContext is, and it being somewhat self-explanatory, while helpful, doesn’t go far enough. As per the documentation, it “creates a Context object. When React renders a component that subscribes to this Context object it will read the current context value from the closest matching Provider above it in the tree.” <a href="https://reactjs.org/docs/context.html#reactcreatecontext"><em>9</em></a> This Context object will allow us to carry out the “providing” and “consuming” mentioned above by Wieruch.</p><p>Now, you must be curious as to what this strange array being passed into createContext is, and why it has an empty object and an empty function? We pass this strange array into createContext because we’ll be “providing” a context value (i.e., Provider value) in the form of: a state object <em>and</em> the ability to change that state object (a setter function) by a component or custom Hook through “consumption” (this last part will make more sense when we tie Context back to the custom Hook useFetchPosts we were looking at earlier).</p><p>Looking at line 25 we see that the Context Provider has a value property, and that is the context value mentioned above. This value is an object with an array of state (an object) and dispatch (a function), at this point, it should be apparent why we passed in that “strange” array when creating the Context, but we also need to comprehend what is being referenced by state and the setter function dispatch. <a href="https://upmostly.com/tutorials/how-to-use-the-usecontext-hook-in-react"><em>9</em></a></p><p>If we log the actual Context object we see that in addition to the Provider we also have the “strange” array as the context value we passed into createContext.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Quw-C8Je_shBELeB85Od1A.png" /></figure><p>In order to understand state and the dispatch setter function above we have to understand another in-built Hook, useReducer, and it actually bears much resemblance to the reducers in Redux.</p><p>This Hook, “accepts a reducer of type (state, action) =&gt; newState, and returns the current state paired with a dispatch method” (If you’re familiar with Redux, you already know how this works). The documentation goes on to call this an “alternative” to useState, and expounding that, “useReducer is usually preferable to useState when you have complex state logic (e.g., async processes) that involves multiple sub-values or when the next state depends on the previous one.” <a href="https://reactjs.org/docs/hooks-reference.html#usereducer"><em>10</em></a> This last part really screams “Redux/Redux-Thunk!”</p><p>I trust that your experience with Redux/Redux-Thunk is manifesting familiarity over the reducer function and the switch logic inside of it. In the event that this doesn’t ring a bell, here is a wonderfully succinct explanation, once again, from Wieruch: “…when fetching data, the dispatch function can be used to send information to the reducer function. The object being sent with the dispatch function has a mandatory type property and an optional payload property. The type tells the reducer function which state transition needs to be applied and the payload can additionally be used by the reducer to distill the new state. After all, we only have three state transitions: initializing the fetching process, notifying about a successful data fetching result, and notifying about an erroneous data fetching result.” <a href="https://www.robinwieruch.de/react-hooks-fetch-data"><em>11</em></a></p><p>But before moving on it’s critical to note that, in addition to the reducer and initial state, this Hook can accept a third argument in the form of “the optional init function, which…allow you to lazily create the initial state. This is helpful if you want the initial state to be different depending on a situation…we could create the initial state anywhere, perhaps dynamically, and it will override our initial state”, clarifies Stephen Hartfield. However, I would be remiss if I didn’t emphasize that init is a function, so whatever we want to override the initial state with must be <em>returned</em> by the function being passed in as the third argument to useReducer. <a href="https://alligator.io/react/usereducer/"><em>12</em></a></p><p>Let’s return to our previous discussion of line 25 where we see the Context Provider with the value property. We now understand the part useReducer plays here, and we can deduce the emanation of the returned array with state and dispatch. The Provider is “providing” the state returned from useReducer for any child component to “consume” from this Context.</p><p>But the Provider is also returning the dispatch function, and now we’ll return to the custom Hook useFetchPosts to comprehend how dispatch will be a vehicle for the custom Hook to push fetched data into this Context.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e2abdf814713739692ff190e21ef91eb/href">https://medium.com/media/e2abdf814713739692ff190e21ef91eb/href</a></iframe><p>Given our recent grasp over the Context object, we can reason what we see on line 6, but for the sake of being comprehensive, we should define our third in-built Hook useContext. The documentation does a very good job so I won’t bother rephrasing. It “accepts a context object (the value returned from React.createContext) and returns the current context value for that context.” <a href="https://reactjs.org/docs/hooks-reference.html#usecontext"><em>13</em></a> However, I’ve only presented the relevant section of the definition here, and very shortly, once we look at how components are “consuming” the Context, we’ll revisit the definition in its entirety.</p><p>This custom Hook is relying on the dispatch function from the PostsContext and using it in the useEffect async code to stagger the data fetch process, and in every stage pass a type string to the Context to convey the fetch stage it’s currently in. What you see is akin to an action creator in Redux/Redux-Thunk, hence the familiarity.</p><p>And that’s it, we use custom Hooks to change the state in Context, and then that Context supplies the state out to the components that are Consumers of the Provider the Context is tied to.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7e3hGUYZt3vLuw0YJQR7qA.png" /></figure><p>The diagram above shows our flow so far, with the starting blue component being &lt;Input /&gt;, and the ending blue component being &lt;Posts /&gt; (which we will discuss next). James King does a phenomenal job of bringing this home and helps us understand the significance of this unique design pattern. “Rather than importing the Context directly in our component, we’re utilizing the custom Hook’s helper functions to interact with the Context state. That means our React components are much leaner because we can simply call those functions from event handlers. We’re importing the custom Hook…to bring in all of those useful helper functions that interact with the Context state.” <a href="https://upmostly.com/tutorials/how-to-use-the-usecontext-hook-in-react"><em>9</em></a></p><p>Now that we comprehend, and appreciate, our new Hooks design pattern a little more, let’s study how components “consume” Context by moving over to the &lt;Posts /&gt; component.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a4f3e2cac90a2f4a978479ee5940e6d9/href">https://medium.com/media/a4f3e2cac90a2f4a978479ee5940e6d9/href</a></iframe><p>On line 5 we’re using useContext to access state from PostsContext, but unlike in the custom Hook discussed above, we’re only using the state object, we don’t needdispatch because we’re not fetching data directly from this component. This component’s job is simply to access the PostsContext for state and then render that data. So it appears that this component is “consuming” Context, but how is it being “provided” the Context? The Context provision isn’t occurring purely through useContext, but in tandem, with the Context Provider we explored earlier.</p><p>Revisiting the complete definition of useContext will help shed more light on this. Referring back to the official documentation, useContext “accepts a context object (the value returned from React.createContext) and returns the current context value for that context. The current context value is determined by the value prop of the nearest &lt;MyContext.Provider&gt; above the calling component in the tree. When the nearest &lt;MyContext.Provider&gt; above the component updates, this Hook will trigger a re-render with the latest context value passed to that MyContext provider. A component calling useContext will always re-render when the context value changes.” <a href="https://reactjs.org/docs/hooks-reference.html#usecontext"><em>13</em></a></p><p>Examining the part of the definition above where it mentions that the, “current context value is determined by the value prop of the nearest &lt;MyContext.Provider&gt; above the calling component in the tree” will undoubtedly raise questions. “Where is this?”, you’ll enquire. To answer that question we now have to look at our &lt;App /&gt; component (below), and there, on lines 19 to 30, we have the PostsContextProvider, and it wraps all components that have the Posts Context as a dependency.</p><p>For example, &lt;Input /&gt;, which we started this exercise with isn’t directly dependent on the Posts Context, but it relies on the useFetchPosts custom Hook’s callback to initiate the data fetch, and the custom Hook uses the Post Context’s dispatch function to store the fetched data in the Context. Through a single degree of separation, &lt;Input /&gt; is dependent on the Posts Context, so it must be wrapped by the respective Provider. &lt;Posts /&gt; must be wrapped as well, and this is clear given the conversation right above.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/44cb07493841ce95559b73401fcb0aa9/href">https://medium.com/media/44cb07493841ce95559b73401fcb0aa9/href</a></iframe><p>In keeping with the topic of Providers, let’s look at another nuanced example to reinforce our understanding, especially with respect to the mandated parent-child relationship.</p><p>In the &lt;App /&gt; component above, you see several child components and two Providers. We know of &lt;PostsContextProvider&gt; since we just worked with it. But where did &lt;CommentsContextProvider&gt; come from? &lt;CommentsContextProvider&gt; comes from another Context in the project I created to better illustrate this example. This other Context uses the same logic to fetch data from the JSONPlaceholder API, it just fetches Comments instead.</p><p>This new Context wraps all other components, and also &lt;PostsContextProvider&gt;, because our &lt;Input /&gt; component, in addition to its dependence on the Posts Context, is also dependent on the Comments Context. This new Comments Context follows the same logic as the Posts Context, so the custom HookuseFetchComments returns a callback function to &lt;Input /&gt; and fetches Comments, then storing them to the Comments Context. (You can find this on line 7 of &lt;Input /&gt;). Ok, that makes sense, &lt;Input /&gt; needs to be wrapped by the Comments Context because of the dependence, but is that it? No, there’s more to examine in this &lt;App /&gt; component.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qMlMQ_bimtcb0uLhkfAPYA.png" /></figure><p>The components wrapped within&lt;PostsContextProvider&gt; (green dotted border) can also “consume” the Comments Context state if they wanted to since &lt;CommentsContextProvider&gt; (blue dotted border) is the “grandparent” to these components. However, the same equivalence can’t be drawn for &lt;Comments /&gt;. This component, by virtue of being outside the &lt;PostsContextProvider&gt; wrapper, does not have access to the Posts Context, it only has access to the Comments Context.</p><p>I wanted to provide this example to illustrate the extra work you might have to put in when architecting your application, and this also serves to demonstrate one of the major drawbacks of using Hooks.</p><p>With Hooks (at least to me), there seems to be no central store for all components to “subscribe” to, similar to what Redux achieves with the combineReducer function. When using Hooks, Providers must be implemented thoughtfully and, in some cases, sparingly as they can only supply global state objects to their children.</p><p>BUT, while Context and Providers may appear limiting at first, upon further scrutiny, especially when juxtaposed with Redux, it comes out on top as a more efficient, less abstract, and easier-to-adopt state management tool.</p><p>At a very basic level, it’s difficult to reconcile why <em>all</em> your components need access to <em>all</em> state objects in a global store, especially if components aren’t dependent on each and every state object.</p><p>The Hooks methodology compels us to invest more thought and planning into the state architecture, in effect, turning the entire application more efficient and secure. Since we don’t have a global store as we did with Redux, we must design the state architecture in a way so that only components that require a specific state object can access that state object. In Hooks parlance, our Providers should only contain relevant child components.</p><p>As our applications gain complexity, it will be paramount to enact an architecture focused on achieving an optimal balance between state isolation and separation, and application-wide state dissemination.</p><p>Let’s consider a social media Facebook-esque application. OAuth data could be supplied to all components to ensure that the user is logged in and that the component has access to login credentials/tokens to fetch appropriate data. Whereas more granular data like a specific user’s comments on a particular post should only be “provided” to the &lt;Comments /&gt; component and nowhere else.</p><p>Another benefit that ought to be highlighted (assuming you’re currently not using <em>any</em> global state management tool) is that Hooks helps in evading issues related to “props drilling”. “Props drilling” was mentioned prior, but it’s worth repeating. Kent Dodds says, “as an application grows, you may find yourself drilling through many layers of components. It’s not normally a big deal when you write it out initially, but after that code has been worked in for a few weeks, things start to get unwieldy”. <a href="https://kentcdodds.com/blog/prop-drilling#what-problems-can-prop-drilling-cause"><em>14</em></a></p><p>That’s it! I hope this was an informative and useful tutorial. If you have any questions or comments (or want to flag typos/grammatical errors :|) please leave them below. And follow me on <a href="https://twitter.com/refayat_haque">Twitter</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=45d154e444a5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>