<?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 Dev Kadiem on Medium]]></title>
        <description><![CDATA[Stories by Dev Kadiem on Medium]]></description>
        <link>https://medium.com/@kadiemq?source=rss-dc4df8382ae9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*e6sBaUugDuEH5JcssvwyXA.png</url>
            <title>Stories by Dev Kadiem on Medium</title>
            <link>https://medium.com/@kadiemq?source=rss-dc4df8382ae9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 03:33:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kadiemq/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[Advanced ReactJS Tutorial: Master Context In A Few Simple Examples]]></title>
            <link>https://medium.com/@kadiemq/advanced-reactjs-tutorial-master-context-in-a-few-simple-examples-845a6c795e10?source=rss-dc4df8382ae9------2</link>
            <guid isPermaLink="false">https://medium.com/p/845a6c795e10</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Dev Kadiem]]></dc:creator>
            <pubDate>Fri, 31 Mar 2023 12:30:09 GMT</pubDate>
            <atom:updated>2023-03-31T12:36:55.526Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3bqdJagRzZCQeOjf79_BAA.jpeg" /><figcaption>ReactJS logo</figcaption></figure><p>React Context transfers data between different levels of your application without &quot;Prop Drilling.&quot; It provides a way to pass data through the components tree.</p><h3>Prop <strong>Drilling</strong></h3><p>To further understand react Context, we must first understand the problem it solves. Prop drilling occurs when we continue passing data to child components in an endless way, even though some of those components don&#39;t use it; they receive it to pass it to their children.</p><p>Let&#39;s take a typical example, a counter app.</p><pre>export default function App() {<br>  const [counter, setCounter] = useState(0);<br><br>  return (<br>    &lt;div&gt;<br>      &lt;AddOneButton setCounter={setCounter} /&gt;<br>      &lt;Counter counter={counter} /&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>It has two children components, one to increase the count and another to show the current count.</p><pre>const AddOneButton = ({setCounter}) =&gt; {<br>  return (<br>    &lt;button onClick={() =&gt; setCounter((value) =&gt; value + 1)}&gt;Add One&lt;/button&gt;<br>  )<br>}<br><br>const Counter = ({counter}) =&gt; {<br>  return (<br>    &lt;p&gt;Count: {counter}&lt;/p&gt;<br>  )<br>}</pre><p>Now let us say we have a new component called Container that wraps the AddOneButton .</p><pre>const Container = ({setCounter}) =&gt; {<br>  return &lt;AddOneButton setCounter={setCounter} /&gt;<br>}</pre><p>And now, inside the App we render the new Container component.</p><pre>&lt;Container setCounter={setCounter} /&gt;</pre><p>Now it&#39;s clear that Container acutely does not need thesetCounter function, we passed it just because AddOneButton needs it, and this what known as &quot;Prop Drilling&quot; this is why we need the Context Api.</p><h3>NOTE</h3><p>In this case, we can mitigate the use of prop drilling by making the Container component a generic component and passing AddOneButton as a child.</p><pre>const Container = ({children}) =&gt; {<br>  return (<br>    {children}<br>  )<br>}<br><br>export default function App() {<br>  const [counter, setCounter] = useState(0);<br><br>  return (<br>    &lt;div&gt;<br>      &lt;Container&gt;<br>        &lt;AddOneButton setCounter={setCounter} /&gt;<br>      &lt;/Container&gt;<br><br>      &lt;Counter counter={counter} /&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><h3>Context with useState</h3><p>now that we understand prop drilling, we can start using Context Api, but before that, we need to decide what way we will implement Context; there are mainly two ways either with useState or useReducer in this section, we will do it using useState , let us start by importing the required modules.</p><pre>import {createContext, useContext} from &quot;react&quot;;</pre><p>Then we create the Context and its provider.</p><pre>export const CounterContext = createContext(null);<br><br>export const CounterContextProvider = ({ children }) =&gt; (<br>  &lt;CounterContext.Provider value={useState(0)}&gt;<br>    {children}<br>  &lt;/CounterContext.Provider&gt;<br>);</pre><p>the createContext function initializes the Context, the provider will wrap our application (only the components inside the provider will have access to data), and because we are using context API we don&#39;t need to pass anything to Container or Counter components.</p><pre>export default function App() {<br>  return (<br>    &lt;CounterContextProvider&gt;<br>      &lt;Container /&gt;<br>      &lt;Counter /&gt;<br>    &lt;/CounterContextProvider&gt;<br>  );<br>}</pre><p>Now to access the data, we shall use useContext hook.</p><pre>const Container = () =&gt; {<br>  return &lt;AddOneButton /&gt;;<br>};<br><br>const AddOneButton = () =&gt; {<br>  const [, setCounter] = useContext(CounterContext);<br>  return (<br>    &lt;button onClick={() =&gt; setCounter((value) =&gt; value + 1)}&gt;Add One&lt;/button&gt;<br>  );<br>};<br><br>const Counter = () =&gt; {<br>  const [counter] = useContext(CounterContext);<br>  return &lt;p&gt;Count: {counter}&lt;/p&gt;;<br>};</pre><h3>Context with useReducer</h3><p>Note: It&#39;s recommended to use useReducer if our state is more complex.</p><p>Let us start by importing the required modules.</p><pre>import { createContext, useContext, useReducer } from &quot;react&quot;;</pre><p>Now let&#39;s create a reducer and plug it into our context data.</p><pre>const reducer = (state, action) =&gt; {<br>  switch(action.type) {<br>    case &quot;increment&quot;:<br>      return state + 1;<br>    default:<br>      return state<br>  }<br>}<br><br>export const CounterContext = createContext(null);<br><br>export const CounterContextProvider = ({ children }) =&gt; (<br>  &lt;CounterContext.Provider value={useReducer(reducer, 0)}&gt;<br>    {children}<br>  &lt;/CounterContext.Provider&gt;<br>);</pre><p>The hook returns a tuple, the first element is the value, and the second is the dispatch function.</p><pre>const Container = () =&gt; {<br>  return &lt;AddOneButton /&gt;;<br>};<br><br>const AddOneButton = () =&gt; {<br>  const [, dispatch] = useContext(CounterContext);<br>  return (<br>    &lt;button onClick={() =&gt; dispatch({type: &quot;increment&quot;})}&gt;Add One&lt;/button&gt;<br>  );<br>};<br><br>const Counter = () =&gt; {<br>  const [counter] = useContext(CounterContext);<br>  return &lt;p&gt;Count: {counter}&lt;/p&gt;;<br>};</pre><p>And basically, that&#39;s how context Api works.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=845a6c795e10" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Typescript, NextJS, Strapi, and GraphQL: An Overview Of How I Created My Blog]]></title>
            <link>https://medium.com/@kadiemq/typescript-nextjs-strapi-and-graphql-an-overview-of-how-i-created-my-blog-d7a592e55f55?source=rss-dc4df8382ae9------2</link>
            <guid isPermaLink="false">https://medium.com/p/d7a592e55f55</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Dev Kadiem]]></dc:creator>
            <pubDate>Fri, 03 Feb 2023 04:48:18 GMT</pubDate>
            <atom:updated>2023-02-03T04:48:18.096Z</atom:updated>
            <content:encoded><![CDATA[<p>First things first, let&#39;s introduce the stack we are going to use. Typescript is &quot;Is a strongly typed programming language that builds on JavaScript, giving you better tooling at any scale.&quot; in simple words, Typescript enhances coding safety and enables more OOP for the web.</p><p>NextJS is a framework that &quot;Enables you to create full-stack web applications by extending the latest React features&quot; in simple words, NextJS is an upgrade over the widely used ReactJS library.</p><p>Strapi is an open-source headless CMS. CMS stands for &quot;content management system,&quot; allowing us to create, manage, modify, and publish content in a user-friendly interface without programming knowledge. Headless means there is no built-in end-user UI; we can use whatever frontend technology we want.</p><p>GraphQL is &quot;A query language for APIs and a runtime for fulfilling those queries with your existing data&quot; in simple words, it&#39;s a language used to query data and get the fields you want.</p><p>Note: this is an overview, which means there are aspects I will not go over, such as styling and best HTML tags; this blog is meant to showcase the functionality of creating a Blog using the technologies mentioned above.</p><h3>Initializing The Project</h3><p>Now, let&#39;s create the folders using the command line (because it&#39;s cooler), so the first command is to create a folder containing all our files.</p><pre>mkdir my-personal-website</pre><p>Now, let&#39;s create folders for both NextJS and Strapi.</p><pre>cd my-personal-website<br>mkdir frontend, strapi</pre><h4>Initialize Strapi</h4><pre>cd strapi<br>npx create-strapi-app@latest . --ts --quickstart</pre><p>Parameter @latest means it will install the latest version, . means we want to create the project in the current folder, then — ts means it will use TypeScript, and lastly — quickstart it will install with default settings; when the installation finishes, it will open a new window on the address <a href="http://localhost:1337/admin/auth/register-admin">/admin/auth/register-admin</a>, asking you to create a new admin account; go ahead and create a new account. Note: using — ts is optional since I won&#39;t change the source code in this post.</p><h4>Initialize NextJS</h4><pre>cd frontend<br>npx create-next-app@latest . --ts</pre><p>And lastly, remember to init a Github repo, but I&#39;ll not cover it in this post.</p><h3>Starting with Strapi</h3><p>I like to start with the backend in my projects, so I will start with Strapi as it&#39;s considered a backend.</p><h4>Installing Graphql</h4><p>One advantage of using Strapi is its easy integration with Graphql. To install the Graphql plugin, we need the run the following command.</p><pre>npm run strapi install graphql</pre><p>If you encounter the <strong><em>Duplicate &quot;graphql&quot; modules</em></strong><em> </em>error, don&#39;t worry; it&#39;s easy to fix; all you need to do is to delete the <strong><em>node_modules</em></strong> folder and <strong><em>package-lock.json</em></strong>, then we need to reinstall packages.</p><pre>rm node_modules<br>rm package-lock.json<br>npm install<br>npm run strapi dev</pre><p>After successful installation, we can now visit the URL <a href="http://localhost:1337/graphql">/graphql</a>.</p><h4>Creating The Blog Post Collection</h4><p>Open the Strapi homepage on URL <a href="http://localhost:1337/admin/">http://localhost:1337/admin/</a>, and after you sign in, go to the <strong><em>Content-Type Builder</em></strong> page, click on <strong><em>Create new collection type </em></strong>button, then<strong><em> </em></strong>in the <strong><em>Display name</em></strong> field, fill it in with an appropriate name; I will choose <strong><em>Blog Post</em></strong>, then click continue.</p><p>Now, we are in fields selection for our new collection; you can customize it however you want; for the sake of simplicity, I will add three fields, a <strong><em>Text</em></strong> field for the title, another <strong><em>Text</em></strong> field for the description, and lastly, a <strong><em>Rich Text</em></strong> field for the body, next click save.</p><p>Now that we have a collection, we need to populate it with data, go to <strong><em>Content Manager</em></strong>, and now we can see the newly created collection, click on it, then <strong><em>Create new entry</em></strong> button, and fill it with any data you want, then click save and publish.</p><h4>Accessibility Option 1: Publicly Accessible</h4><p>Before we can access our data through Graphql, we need to make it accessible; you can make it publicly accessible or only for authenticated users. I will choose a publicly accessible collection since I&#39;m not storing sensitive data.</p><p>To access it publicly, go to <strong><em>Settings, </em></strong>then roles, click on <strong><em>Public</em></strong>, scroll down to the collection you created (in my case, it&#39;s Blog-post), click it, then tick <strong><em>find</em></strong> and <strong><em>findOne.</em></strong></p><h4>Accessibility Option 2: Authenticated Only</h4><p>However, should you choose the authenticated way, here is how to do it. There are two ways to achieve this; the first one is to create <strong><em>API Token</em></strong> in the settings page, then we need to attach it with our requests by adding it to the headers as an <strong><em>Authorization</em></strong> header and setting the value to be <strong><em>bearer &lt;API Token&gt;</em></strong>, the second way is to create a new entry in the <strong><em>User </em></strong>collection, via <strong><em>Content Manager</em></strong> page, then send a <strong><em>Post</em></strong> request to <a href="http://127.0.0.1:1337/api/auth/local">http://</a><a href="http://localhost:1337/admin/">localhost</a><a href="http://127.0.0.1:1337/api/auth/local">:1337/api/auth/local</a> with an attached JSON body containing identifier which could be either the username or email, and password, of the newly created user in the <strong><em>User</em></strong> collection, <strong>NOT THE ADMIN ACCOUNT WE CREATED IN INITIALIZE STRAPI.</strong></p><pre>{<br> &quot;identifier&quot;: &quot;email or username&quot;,<br> &quot;password&quot;: &quot;password&quot;<br>}</pre><p>If the request were successful, you would get a response containing the <strong><em>JWT</em></strong> field, and now we need to do the same thing, send it with each request via headers in an <strong><em>Authorization</em></strong> header and set the value to be <strong><em>bearer &lt;API Token&gt;.</em></strong></p><p>Now to access it, go to <strong><em>Settings, </em></strong>then roles, click on <strong><em>Authenticated</em></strong>, scroll down to the collection you created (in my case, it&#39;s Blog-post), click it, then tick <strong><em>find</em></strong> and <strong><em>findOne.</em></strong></p><h4>Testing Graphql Endpoint</h4><p>To access Graphql go to <a href="http://localhost:1337/graphql">http://localhost:1337/graphql</a>, and now, we can see the input field on the left side; here, we will put our queries to query our Strapi application, an example of a query:</p><pre>query {<br>  blogPosts {<br>    data {<br>      id<br>      attributes {<br>        title<br>        description<br>        body<br>      }<br>    }<br>  }<br>}</pre><p>And in my case, the response is:</p><pre>  &quot;data&quot;: {<br>    &quot;blogPosts&quot;: {<br>      &quot;data&quot;: [<br>        {<br>          &quot;id&quot;: &quot;1&quot;,<br>          &quot;attributes&quot;: {<br>            &quot;title&quot;: &quot;test&quot;,<br>            &quot;description&quot;: &quot;test&quot;,<br>            &quot;body&quot;: &quot;test&quot;<br>          }<br>        }<br>      ]<br>    }<br>  }<br>}</pre><h4>Testing Rest Endpoint</h4><p>All we need to do is send a GET request to <a href="http://127.0.0.1:1337/api/blog-posts/">http://127.0.0.1:1337/api/&lt;your collection&gt;/</a>. An example of a response would be:</p><pre>{<br>    &quot;data&quot;: [<br>        {<br>            &quot;id&quot;: 1,<br>            &quot;attributes&quot;: {<br>                &quot;title&quot;: &quot;test&quot;,<br>                &quot;description&quot;: &quot;test&quot;,<br>                &quot;body&quot;: &quot;test&quot;,<br>                &quot;createdAt&quot;: &quot;2023-01-30T20:28:28.141Z&quot;,<br>                &quot;updatedAt&quot;: &quot;2023-01-30T20:28:29.027Z&quot;,<br>                &quot;publishedAt&quot;: &quot;2023-01-30T20:28:29.025Z&quot;<br>            }<br>        }<br>    ],<br>    &quot;meta&quot;: {<br>        &quot;pagination&quot;: {<br>            &quot;page&quot;: 1,<br>            &quot;pageSize&quot;: 25,<br>            &quot;pageCount&quot;: 1,<br>            &quot;total&quot;: 1<br>        }<br>    }<br>}</pre><p>We have finished the Strapi section and will continue with NextJS.</p><h3>Starting With NextJS</h3><p>Create a new directory inside the <strong><em>pages</em></strong> directory and name it <strong><em>blog</em></strong>; next, create a new index.tsx file and initialize a basic react component.</p><pre>import {NextPage} from &quot;next&quot;;<br><br>interface Props {<br>}<br><br>const About: NextPage&lt;Props&gt; = (Props) =&gt; {<br>    return (<br>        &lt;p&gt;About Page&lt;/p&gt;<br>    )<br>}<br><br>export default About;</pre><p>Now we are to visit <a href="http://localhost:3000/blog">http://localhost:3000/blog</a> and view the About Page.</p><h4>Creating Interfaces</h4><p>We will need a few interfaces; let&#39;s start by creating a <strong><em>common</em></strong> folder containing all of our basic modules, then create another folder called <strong><em>types</em></strong> which will contain all our types and interfaces then create a new typescript I will name <strong><em>BlogInterfaces</em></strong>; now let the first interface, which is going to IBlogIdentification and it will contain our identification field; in our case, it&#39;s the id of the blog post.</p><pre>export interface IBlogIdentification {<br>    id: string<br>}</pre><p>Next, we need an interface to hold the blog fields&#39; title, description, and body; name it IBlogFields.</p><pre>export interface IBlogFields {<br>    title: string,<br>    description: string,<br>    body: string<br>}</pre><p>Next, we need an interface for blog attributes we will receive from the GraphQL query; name it IBlogAttributes.</p><pre>export interface IBlogAttributes {<br>    attributes: Partial&lt;IBlogFields&gt; &amp; Pick&lt;IBlogFields, &#39;title&#39;&gt;<br>}</pre><p>I have used Partial and Pick utility types to make all of IBlogFields fields optional except title.</p><p>Lastly, we will need an interface to handle the whole blog entry; name it IBlog.</p><pre>export interface IBlog extends IBlogIdentification, IBlogAttributes{}</pre><p>Now let&#39;s update the Props interface on the <strong><em>blog</em></strong> page.</p><pre>interface Props {<br>    blogs: IBlog[]<br>}</pre><h4>GraphQL Works</h4><p>Before we start fetching data, we need to do GraphQL Works. First, we need to install two packages to be able to interact with GraphQL; we will need the graphql and @apollo/client packages.</p><pre>npm i graphql, @apollo/client</pre><p>Second, we need to write the queries; we will need three queries, the first to list blogs, the second is to get a single blog, and the third is to get the list of blog Ids&#39;; in the <strong><em>common</em></strong> folder, create a new folder and call it graphql, then create a new file and call it queries, and add the following queries.</p><pre>export const LIST_BLOG = gql(`query {<br>  blogPosts {<br>    data {<br>      id<br>      attributes {<br>        title<br>      }<br>    }<br>  }<br>}`)<br><br>export const SINGLE_BLOG = gql(`query ($blogId: string!) {<br>  blogPosts(filters: {id: {eq: $blogId}}) {<br>    data {<br>      id<br>      attributes {<br>        title<br>        description<br>        body<br>      }<br>    }<br>  }<br>}`)<br><br>export const LIST_ID = gql(`query {<br>  blogPosts {<br>    data {<br>      id<br>    }<br>  }<br>}`)</pre><p>The third thing we need is to store Strapi&#39;s address, and the most convenient way is to store it inside the <strong><em>env</em></strong> variables; NextJS already comes with a built-in environment variable module, so there is no need to install dotenv, all we need to do is to go to next-config.js, and add the following export.</p><pre>module.exports = {<br>  env: {<br>    STRAPI_ADDRESS: &quot;http://127.0.0.1:1337/graphql&quot;<br>  },<br>  nextConfig,<br>}</pre><p>And the last thing we need is an ApolloClient to be to connect with the GraphQL server, inside the <strong><em>graphql</em></strong> folder, create a new file and name it client, then add the following code.</p><pre>import {ApolloClient, InMemoryCache, NormalizedCacheObject} from &quot;@apollo/client&quot;;<br><br>const client: ApolloClient&lt;NormalizedCacheObject&gt; = new ApolloClient({<br>    uri: process.env.STRAPI_ADDRESS,<br>    cache: new InMemoryCache(),<br>});<br><br>export default client;</pre><p>Note: the cache is a way for the ApolloClient to cache results, it&#39;s a big topic and out of scope for this post. More info can be found <a href="https://www.apollographql.com/docs/react/caching/overview">here</a>.</p><h4>Fetching Data</h4><p>Now we can start implementing the fetching procedure; let&#39;s start by creating the getStaticProps function:</p><pre>export const getStaticProps: GetStaticProps&lt;Props&gt; = async () =&gt; {<br>    <br>}</pre><p>We are going to use getStaticProps because it will pre-render the page at build time, and the data will not be changing consistently; there is no need to send a request to our CMS every time.</p><p>Now we can start querying Strapi; let&#39;s get a list of blogs.</p><pre>    const {data} = await client.query({query: LIST_BLOG})<br>    const blogs: IBlog[] = data.blogPosts.data;<br>    <br>    return {<br>        props: {<br>            blogs<br>        }<br>    }</pre><h4>Displaying Blog List</h4><p>Now that we can retrieve a list of blogs, we can start displaying them; we need new folders. To make it easier, I will show a demo below of my project structure.</p><pre>common<br>--elements<br>----blog<br>------BlogTitle.tsx<br><br><br><br>modules<br>--blog<br>----BlogCardList.tsx</pre><p>We need two files, BlogTitle will render the title of a blog, and BlogCardList will use BlogTitle to render a list of blogs, let&#39;s start with BlogTitle.</p><pre>interface Props  {<br>    title: string<br>    isClickable: boolean<br>    blogId?: string<br>}<br><br>const BlogTitle: NextPage&lt;Props&gt; = ({title, isClickable, blogId}) =&gt; {<br>    if(isClickable &amp;&amp; blogId) {<br>        return (<br>            &lt;Link href={`/blog/${blogId}`}&gt;{title}&lt;/Link&gt;   <br>        )<br>    } else {<br>        return (<br>            &lt;p&gt;{title}&lt;/p&gt;<br>        )<br>    }<br>}</pre><p>Note: Because I know in the commercial version, I will be using the blog title in multiple locations, and it will have more props and functionality attached to it, I chose to make the blog title a separate component; however, you can choose not to.</p><p>Now to the list of cards.</p><pre>interface Props {<br>    blogs: IBlog[]<br>}<br><br>const BlogCardList: NextPage&lt;Props&gt; = ({blogs}) =&gt; {<br>    return (<br>        &lt;div&gt;<br>            {blogs.map((blog, i) =&gt; {<br>                return (<br>                    &lt;div key={i}&gt;<br>                        &lt;BlogTitle <br>                            title={blog.attributes.title} <br>                            isClickable={true} <br>                            blogId={blog.id}<br>                        /&gt;<br>                    &lt;/div&gt;<br>                );<br>            })}<br>        &lt;/div&gt;<br>    )<br>}<br><br>export default BlogCardList;</pre><p>Now to show the list, we need to add BlogCardList to about page.</p><pre>const Blog: NextPage&lt;Props&gt; = ({blogs}) =&gt; {<br>    return (<br>        &lt;BlogCardList blogs={blogs}/&gt;<br>    )<br>}</pre><p>Now if we go to <a href="http://localhost:3000/blog">http://localhost:3000/blog</a>, we should see a list of blog titles.</p><h4>Displaying A Single Blog Post</h4><p>Let&#39;s start creating the individual blog post page, create a new file, and call it [id].tsxinside the <strong><em>blog</em></strong> directory inside the <strong><em>pages </em></strong>directory, initialize a new basic react component.</p><pre>import {NextPage} from &quot;next&quot;;<br>import {IBlog} from &quot;@/common/types/BlogInterfaces&quot;;<br><br>interface Props {<br>    blog: IBlog<br>}<br><br>const client = new ApolloClient({<br>    uri: process.env.STRAPI_ADDRESS,<br>    cache: new InMemoryCache()<br>});<br><br>const Blog: NextPage&lt;Props&gt; = ({blog}) =&gt; {<br>    return (<br>        &lt;p&gt;Blog Here&lt;p/&gt;<br>    )<br>}<br><br>export default Blog;</pre><p>We are going to utilize NextJS&#39;s getStaticPaths and getStaticProps functions, more info can be found <a href="https://nextjs.org/docs/api-reference/data-fetching/get-static-paths">here</a>.</p><pre>export const getStaticPaths: GetStaticPaths = async () =&gt; {<br>    const {data} = await client.query({query: LIST_ID })<br>    const ids: IBlogIdentification[] = data.blogPosts.data;<br>    <br>    const paths = ids.map(id =&gt; {<br>        return {params: {...id}}<br>    })<br>    <br>    return {<br>        paths,<br>        fallback: true<br>    }<br>}<br><br>export const getStaticProps: GetStaticProps&lt;Props&gt; = async ({params}) =&gt; {<br>    console.log()<br>    const {data} = await client.query({query: SINGLE_BLOG, variables: {blogId: params!.id}})<br>    const blog: IBlog = data.blogPosts.data[0];<br><br>    return {<br>        props: {<br>            blog<br>        }<br>    }<br>}</pre><p>And now, we can access the blog data inside the component.</p><pre>const Blog: NextPage&lt;Props&gt; = ({blog}) =&gt; {<br>    console.log(blog)<br>    return (<br>        &lt;div&gt;<br>            &lt;p&gt;{blog.id}&lt;/p&gt;<br>            &lt;p&gt;{blog.attributes.title}&lt;/p&gt;<br>            &lt;p&gt;{blog.attributes.description}&lt;/p&gt;<br>            &lt;p&gt;{blog.attributes.body}&lt;/p&gt;<br>        &lt;/div&gt;<br>    )<br>}</pre><p>Now our blog is functional; we can retrieve and display a list of blogs and a single blog post.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d7a592e55f55" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Upgrade Your Development Skills: Introduction to SOLID Principles]]></title>
            <link>https://medium.com/@kadiemq/upgrade-your-development-skills-introduction-to-solid-principles-f6f6404f72a6?source=rss-dc4df8382ae9------2</link>
            <guid isPermaLink="false">https://medium.com/p/f6f6404f72a6</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[development]]></category>
            <dc:creator><![CDATA[Dev Kadiem]]></dc:creator>
            <pubDate>Thu, 26 Jan 2023 08:26:54 GMT</pubDate>
            <atom:updated>2023-01-26T08:26:54.594Z</atom:updated>
            <content:encoded><![CDATA[<p>A clear distinction between junior and senior developers is how well senior developers future-proof their programs; one way of achieving this is to use a well-known code or rules, like SOLID principles, which Robert C. Martin developed in his essay, “Design Principles and Design Patterns.”</p><p>SOLID is an acronym for single responsibility, open-closed, Liskov substitution, interface segregation, and dependency inversion principle, and it’s important to state that SOLID is mainly for OOP.</p><p>It’s important to recall that this is an introduction; thus, I will use easy scenarios, and the examples shown are for learning purposes only and not for commercial use. Lastly, I’ll use sudo code to make it reachable to most people.</p><h3><strong>Single Responsibility Principle</strong></h3><p>The single responsibility principle states, “<em>A class should have only one reason to change.”</em> According to the previous state, each class is responsible for only one part during the software lifespan.</p><p>To kick off the article, I’ll create a simple User class:</p><pre>class User {<br>    function profile()<br>    function login()<br>    function register()<br>    function sendVerificationEmail()<br>}</pre><p>As we can see, the class is responsible for more than one part, and my way of applying the principles is the following:</p><pre>class User {<br>    function profile()<br>}<br><br>class Authentication {<br>    function login()<br>}<br><br>class Signup {<br>    function register()<br>    function sendVerificationEmail()<br>}</pre><p>We now have three classes, each responsible for only one part.</p><h3>Open Closed Principle</h3><p>The open-closed principle states, “<em>A class should be open to extension but closed to modifying.”</em> According to the previous state, each class should be written in a way that allows the addition of functionality but does not allow alteration of its core.</p><p>To demonstrate a demo of this principle, I’ll create another User class but this time, it will have a variable called type:</p><pre>class User {<br>    var type<br><br>    constructor(var type) {<br>        this.type = type<br>    }<br><br>    function doSomething() {<br>      if(type == &quot;normal&quot;) {<br>        // ...<br>      } else if(type == &quot;professional&quot;) {<br>        // ...<br>      }<br>    }<br><br>    // ...<br>}<br><br>User normalUser = new User(&quot;normal&quot;)<br>User professionalUser = new User(&quot;professional&quot;)</pre><p>The class is open for modification because type has a direct influence on the class’s functionality; this is an example of why we need the open-closed principle. Let’s see an example of how to apply the principle here:</p><pre>abstract class User {<br>    abstract function doSomething()<br>}<br><br>class NormalUser Inherits User {<br>    function doSomething() {<br>      // ...<br>    }<br>}<br><br>class ProfessionalUser Inherits User {<br>    function doSomething() {<br>      // ...<br>    }<br>}<br><br>User normalUser = new NormalUser()<br>User professionalUser = new ProfessionalUser()</pre><p>By implementing the principle, we can write a more precise functionality.</p><h3>Liskov Substitution Principle</h3><p>The Liskov substitution principle states, “<em>if S is a subtype of T, then objects of type T may be replaced with objects of type S”</em> Liskov substitution is better explained with an example:</p><pre>abstract class Employee {<br>    abstract function getBonus()<br>}<br><br>class HardWorkingEmployee Inherits Employee {<br>    function getBonus() {<br>        // ...<br>    }<br>}<br><br>class LackingEmployee Inherits Employee {<br>    function getBonus() {<br>        Error<br>    }<br>}</pre><p>And now, to instantiate an instance of HardWorkingEmployee class:</p><pre>Employee employee = new HardWorkingEmloyee()<br>employee.getBonus()</pre><p>The example above would work perfectly, now let’s change HardWorkingEmployee with LackingEmployee:</p><pre>employee = new LackingEmployee()<br>employee.getBonus()</pre><p>The example above would not work because, LackingEmployee does not implement bonus function, even though they both are of type Employee, and that is a violation of the Liskov Substitution; an easy fix for this situation is the following:</p><pre>abstract class Employee {<br>    // ...<br>}<br><br>interface EligableForBonus {<br>    function getBonus()<br>}<br><br>class HardWorkingEmployee Inherits Employee, EligableForBonus {<br>    function getBonus() {<br>        // ...<br>    }<br>}<br><br>class LackingEmployee Inherits Employee {<br>    // ...<br>}</pre><p>Now LackingEmployee does not inherit any non-implemented functionality.</p><h3>Interface Segregation Principle</h3><p>The interface segregation principle states, “<em>Clients should not be forced to depend upon interfaces that they do not use.</em>” It means that when a class inherits a parent, it should implement all of its functionality.</p><pre>interface UserFunctions {<br>    function function1()<br>    function function2()<br>    function function3()<br>    function function4()<br>}<br><br>class User inherits UserFunctions {<br>    function function1() {<br>      // ..<br>    }<br><br>    function function2() {<br>      // ..<br>    }<br><br>    function function3() {<br>      // ..<br>    }<br><br>    function function4() {<br>      Error<br>    }<br>}</pre><p>The User class does not implement function4 and thus, it violates the interface segregation principle; one way of fixing it is the following:</p><pre>interface CoreUserFunctions {<br>    function function1()<br>    function function2()<br>    function function3()<br>}<br><br>interface ExtraUserFunctions {<br>    function function4()<br>}<br><br>class BasicUser inherits UserFunctions {<br>    function function1() {<br>      // ..<br>    }<br><br>    function function2() {<br>      // ..<br>    }<br><br>    function function3() {<br>      // ..<br>    }<br>}<br><br>class UpgradedUser inherits UserFunctions, ExtraUserFunctions {<br>    function function1() {<br>      // ..<br>    }<br><br>    function function2() {<br>      // ..<br>    }<br><br>    function function3() {<br>      // ..<br>    }<br><br>    function function4() {<br>      // ..<br>    }<br>}</pre><p>Now we have BasicUser and UpgradedUser and both fully implement what they inherit.</p><h3>Dependency Inversion Principle</h3><p>The Dependency Inversion Principle states, “<em>The interaction between high level and low level modules should be thought of as an abstract interaction between them.</em>” It means that if we have interactions between high-level and low-level modules or classes, we should add a middle layer because they both operate at different levels of complexity.</p><pre>class DataAccesslayer {<br>    function saveToDatabase(data) {<br>        // ...<br>    }<br>}<br><br>class User {<br>    DataAccesslayer dataAccesslayer<br>    dataAccesslayer.saveToDatabase(data)<br>}</pre><p>The example above does not implement the Dependency inversion principle, thus any modification to DataAccessLayer might means we need to modify Userclass also, a better implementation would be like this:</p><pre>interface DataAccesslayerInterface {<br>    function saveToDatabase(data)<br>}<br><br>class DataAccesslayer inherits DataAccesslayerInterface {<br>    function saveToDatabase(data) {<br>        // ...<br>    }<br>}<br><br>class User {<br>    DataAccesslayerInterface dataAccesslayer<br>    dataAccesslayer.saveToDatabase(data)<br>}</pre><p>Now we have an abstraction layer, which means that modification on DataAccesslayer will no longer need modification on User class because the abstraction layer does not change; thus function signature does not change</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f6f6404f72a6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python Django: Create a more secure database by using a custom field]]></title>
            <link>https://medium.com/@kadiemq/python-django-create-a-more-secure-database-by-using-a-custom-field-5fb60dd33ea4?source=rss-dc4df8382ae9------2</link>
            <guid isPermaLink="false">https://medium.com/p/5fb60dd33ea4</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Dev Kadiem]]></dc:creator>
            <pubDate>Tue, 17 Jan 2023 17:31:16 GMT</pubDate>
            <atom:updated>2023-01-18T14:45:35.945Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cp8TfohI7A0uzhgnLNCIsg.png" /></figure><p>One way of enhancing the security of a database is by encrypting it. Luckily by utilizing Django, we can do this automatically. We only need the signing and models packages from the core Django packages.</p><p>Let’s start by importing the required packages:</p><pre>from django.core import signing<br>from django.db.models import TextField</pre><p>First, the signing is a cryptographic signing package; it allows encrypting and decrypting using the SECRET_KEY found in settings.py; more info can be found at the bottom, and we need the TextField because we will extend the default one with more functionality.</p><p>Now let’s create and init the new field. I’ll name it EncryptedTextField:</p><pre>class EncryptedTextField(models.TextField):<br>    def __init__(self, *args, **kwargs):<br>        super(EncryptedTextField, self).__init__(*args, **kwargs)</pre><p>Now for the encrypting part:</p><pre>    def get_db_prep_save(self, value, connection):<br>        value = super().get_db_prep_value(value, connection)<br>        if value is None:<br>            return value<br><br>        if len(value) == 0:<br>            return value<br><br>        return ((signing.dumps(str(value))).encode(&#39;utf-8&#39;)).decode(&#39;utf-8&#39;)</pre><p>The get_db_prep_save is a function that runs when we try to save data to the database; we get the raw data by get_db_prep_value and then return an encrypted version of it return ((signing.dumps(str(value))).encode(‘utf-8’)).decode(‘utf-8’). More info can be found at the bottom.</p><p>Now for the decrypting part:</p><pre>    def from_db_value(self, value, *args, **kwargs):<br>        if value is None:<br>            return value<br><br>        if len(value) == 0:<br>            return value<br>        return signing.loads(value)</pre><p>The def from_db_value is a function that runs when we try to get data from the database, value here represents the encrypted data, so we need to decrypt it, which is done here return signing.loads(value). More info can be found at the bottom.</p><p>Example of usage:</p><pre>public_api = EncryptedTextField()</pre><p>Example of a complete code:</p><pre>from django.db.models import TextField<br>from django.core import signing<br><br>class EncryptedTextField(models.TextField):<br>    def __init__(self, *args, **kwargs):<br>        super(EncryptedTextField, self).__init__(*args, **kwargs)<br><br>    def get_db_prep_save(self, value, connection):<br>        value = super().get_db_prep_value(value, connection)<br>        if value is None:<br>            return value<br><br>        if len(value) == 0:<br>            return value<br><br>        return ((signing.dumps(str(value))).encode(&#39;utf-8&#39;)).decode(&#39;utf-8&#39;)<br><br>    def to_python(self, value):<br>        return value<br><br>    def from_db_value(self, value, *args, **kwargs):<br>        if value is None:<br>            return value<br><br>        if len(value) == 0:<br>            return value<br>        return signing.loads(value)</pre><p>Links to more info:</p><p>- The signing package: <a href="https://docs.djangoproject.com/en/4.1/topics/signing/">https://docs.djangoproject.com/en/4.1/topics/signing/</a></p><p>- The get_db_prep_save function:<br><a href="https://docs.djangoproject.com/en/4.1/ref/models/fields/#django.db.models.Field.get_db_prep_save">https://docs.djangoproject.com/en/4.1/ref/models/fields/#django.db.models.Field.get_db_prep_save</a></p><p>- The from_db_value function:<br><a href="https://docs.djangoproject.com/en/4.1/ref/models/fields/#django.db.models.Field.from_db_value">https://docs.djangoproject.com/en/4.1/ref/models/fields/#django.db.models.Field.from_db_value</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5fb60dd33ea4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Do you know why array[index] is n(1)?]]></title>
            <link>https://medium.com/@kadiemq/do-you-know-why-array-index-is-n-1-9af27da72f95?source=rss-dc4df8382ae9------2</link>
            <guid isPermaLink="false">https://medium.com/p/9af27da72f95</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Dev Kadiem]]></dc:creator>
            <pubDate>Tue, 17 Jan 2023 16:18:02 GMT</pubDate>
            <atom:updated>2023-01-17T16:18:02.922Z</atom:updated>
            <content:encoded><![CDATA[<p>When I started working in web development, I had no idea why array[index] is n(1) because I was primarily working with high-level languages, and the mystery continued until I started working with the low-level language Rust.</p><p>To answer why it’s n(1), we must first understand what a pointer is: an object that stores a memory address. Thus when we use a pointer, we are accessing a memory location rather than the underlying data.</p><p>As for the array data structure, an array is a collection of elements stored in a contiguous memory location; it fulfills an entire row of memory addresses with no spaces or gaps between elements.</p><p>Now that we have defined what a pointer and array are, it won’t be a surprise when I say that when we instantiate an array, we create a pointer (The naming differs between languages)</p><p>let arr = [1,2,3,4,5]</p><p>Now that we know that arr is a pointer (with extra data like length and size), it’s safe to say that arr is pointing to the memory address of the first element of the array. In other words, the memory address of arr and the memory address of arr[0] is the same.</p><p>Lastly, an example would make everything clear. Let’s say that arr is in memory location 10, which means that the first element is also in memory location 10; now, assuming that Number in Javascript is 8 Bytes, the second element will be in location 18, and the third will be in 26.</p><p>arr[0] -&gt; stored in memory location 10<br>arr[1] -&gt; stored in memory location 18<br>arr[2] -&gt; stored in memory location 26</p><p>And that is why array[index] is n(1) because all we need to get is the memory location of the first element + (Data size in bytes * index).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9af27da72f95" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>