<?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 Simeon Nortey on Medium]]></title>
        <description><![CDATA[Stories by Simeon Nortey on Medium]]></description>
        <link>https://medium.com/@simeonnortey?source=rss-cd2e550fbad7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*5T0N-f1HLAB5aFHtFfzzaQ.jpeg</url>
            <title>Stories by Simeon Nortey on Medium</title>
            <link>https://medium.com/@simeonnortey?source=rss-cd2e550fbad7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 12:46:32 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@simeonnortey/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[How to Build and Embed AI-Powered Dashboards]]></title>
            <link>https://simeonnortey.medium.com/how-to-build-and-embed-ai-powered-dashboards-10a4b7e309e4?source=rss-cd2e550fbad7------2</link>
            <guid isPermaLink="false">https://medium.com/p/10a4b7e309e4</guid>
            <dc:creator><![CDATA[Simeon Nortey]]></dc:creator>
            <pubDate>Thu, 08 Jan 2026 14:52:33 GMT</pubDate>
            <atom:updated>2026-01-08T14:52:33.858Z</atom:updated>
            <content:encoded><![CDATA[<p>A year ago, I was working closely with a marketing team, and most of our conversations followed the same pattern.</p><p>“How many users do we have today?”<br>“How many of them are from the UK?”<br>“Did this campaign actually bring in new users?”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*DhtHygq-rIpY2lOAu-7cJA.gif" /></figure><p>None of the questions were complicated, but every single one of them required me to go back to the database and write a query. Sometimes it was a small tweak, sometimes a new one entirely. Either way, answering simple questions kept pulling me out of actual development work. <br>After a while, it became obvious that the problem wasn’t the data or the questions; it was the workflow.</p><p>There are already tools that try to solve this problem, things like Metabase, Looker, Redash, and even custom dashboards built on top of charting libraries. They help to some extent, but you still end up defining queries, metrics, and views ahead of time. Someone still has to do that work.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/1*-WYcV8xq-OeaBRQBIFbqGA.gif" /></figure><p>What I actually wanted was to give non-technical users the ability to ask their own questions and get answers directly, without needing a developer in the loop each time. For this article, I’m going to use Papermap. Not because it’s the only tool that can do this, but because it’s easy to set up and makes it straightforward to embed dashboards where users can explore data by asking questions instead of clicking through predefined views.</p><figure><img alt="Minions celebrating lets get started" src="https://cdn-images-1.medium.com/max/220/1*de8juUq-L6WtPIIdsXsuVg.gif" /></figure><p>Let&#39;s get straight into the works. First, visit <a href="https://papermap.ai/">https://papermap.ai</a> and sign up. It has a free plan, so that is also one easy reason to use it. No need to punch in your credit card for a free trial.</p><h3>Connecting Your Data</h3><p>After you login, you will go through the onboarding, and when done, you will be taken to the workspaces page, and then you create a new workspace. So think of the workspace as a folder that contains your files; that is your dashboards.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*87wSrT1Fji5gCAO3bz_0zQ.png" /></figure><p>Papermap has a variety of data sources like Excel, CSV, Postgres, quickbooks and many more you can choose from. Once your data source is connected, you can create one or multiple dashboards within the same workspace. If you’re interested in embedding dashboards inside your own application, Papermap has detailed documentation available here: <a href="https://docs.papermap.ai/">https://docs.papermap.ai/</a> but i am going to take you through a basic one.</p><h3>Creating API Keys</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BbP-3hSwIHq1kybAyUmpCg.png" /></figure><p>To embed dashboards securely, you’ll need API credentials.</p><ol><li>Go to Workspace Settings</li><li>Select the API Keys tab</li><li>Create a new API Key ID and API Secret</li></ol><p>Important: The API secret must be kept on your server and never exposed to the frontend.</p><h3>Generating an Embed Token (Next.js Example)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YYlUmzRo9q8stIaqrKNSUA.png" /></figure><p>After you get this, you can use the api secret to generate an embedded token for embedding your dashboard. There is an example here <a href="https://docs.papermap.ai/documentation/embedding/basic-embedding">https://docs.papermap.ai/documentation/embedding/basic-embedding</a></p><p>For security reasons you have to keep your secret key on your server. Papermap uses a secure, signed embed token to authorize dashboard access. This token must be generated server-side.</p><p>However if you want to quickly test your iframe you can use papermap’s TEST API</p><pre>POST https://papermap.ai/api/v1/embed/generate-token<br><br>Example Request<br>{<br>  &quot;workspace_id&quot;: &quot;&quot;,<br>  &quot;api_key_id&quot;: &quot;&quot;,<br>  &quot;secret_key&quot;: &quot;&quot;,<br>  &quot;dashboard_id&quot;: &quot;&quot;,<br>  &quot;validity_duration&quot;: 3600<br>}</pre><h3>Important Notes About the Test API</h3><ol><li><strong>This endpoint is for testing and development only</strong></li><li><strong>Do not use this in production</strong></li><li><strong>Never expose your secret key in frontend code</strong></li></ol><p>In a real production setup, the <strong>secret key must always stay on your server</strong>, and the token should be generated using your own backend logic (like the Next.js example shown earlier).</p><p>Think of this test endpoint as a <strong>sandbox</strong> it helps you understand the embedding flow before implementing it properly.</p><p>Below is an example using <strong>Next.js (App Router)</strong>.</p><pre>import { NextRequest, NextResponse } from &#39;next/server&#39;<br>import crypto from &#39;crypto&#39;<br><br>// Server-side secret key - stored securely as environment variable<br>const EMBED_SECRET_KEY = process.env.EMBED_SECRET_KEY || &#39;&#39;<br><br><br>interface GenerateTokenOptions {<br>    workspace_id: string<br>    api_key_id: string<br>    dashboard_id?: string<br>    validity_duration?: number<br>}<br><br>interface TokenData {<br>    api_key_id: string<br>    workspace_id: string<br>    dashboard_id?: string<br>    valid_until: number<br>    signature: string<br>}<br><br>const DEFAULT_VALIDITY_DURATION = 3600 // 1 hour in seconds<br><br>function generateEmbeddingToken(options: GenerateTokenOptions): {<br>    token: string<br>    validUntil: number<br>} {<br>    const {<br>        workspace_id,<br>        api_key_id,<br>        dashboard_id,<br>        validity_duration = DEFAULT_VALIDITY_DURATION,<br>    } = options<br><br>    const validUntil = Math.floor(Date.now() / 1000) + validity_duration<br><br>    // Create payload for signature using server-side secret key<br>    const payload = `${workspace_id}${validUntil}`<br>    const signature = crypto.createHmac(&#39;sha256&#39;, EMBED_SECRET_KEY).update(payload).digest(&#39;hex&#39;)<br><br>    // Build token data<br>    const tokenData: TokenData = {<br>        api_key_id,<br>        workspace_id,<br>        valid_until: validUntil,<br>        signature,<br>    }<br><br>    // Only include dashboard_id if provided<br>    if (dashboard_id) {<br>        tokenData.dashboard_id = dashboard_id<br>    }<br><br>    // Encode token as base64url<br>    const token = Buffer.from(JSON.stringify(tokenData)).toString(&#39;base64url&#39;)<br><br>    return { token, validUntil }<br>}<br><br>export async function POST(request: NextRequest) {<br>    try {<br>        // Check if secret key is configured<br>        if (!EMBED_SECRET_KEY) {<br>            return NextResponse.json(<br>                { error: &#39;Server configuration error: EMBED_SECRET_KEY not configured&#39; },<br>                { status: 500 }<br>            )<br>        }<br><br>        const body = await request.json()<br>        const {<br>            workspace_id,<br>            api_key_id,<br>            dashboard_id,<br>            validity_duration,<br>        } = body as GenerateTokenOptions<br><br>        // Validate required fields<br>        const missingFields: string[] = []<br>        if (!workspace_id) missingFields.push(&#39;workspace_id&#39;)<br>        if (!api_key_id) missingFields.push(&#39;api_key_id&#39;)<br><br>        if (missingFields.length &gt; 0) {<br>            return NextResponse.json(<br>                { error: `Missing required fields: ${missingFields.join(&#39;, &#39;)}` },<br>                { status: 400 }<br>            )<br>        }<br><br>        // Validate validity_duration if provided<br>        if (validity_duration !== undefined) {<br>            if (typeof validity_duration !== &#39;number&#39; || !Number.isInteger(validity_duration)) {<br>                return NextResponse.json(<br>                    { error: &#39;validity_duration must be an integer&#39; },<br>                    { status: 400 }<br>                )<br>            }<br>            if (validity_duration &lt;= 0) {<br>                return NextResponse.json(<br>                    { error: &#39;validity_duration must be a positive integer&#39; },<br>                    { status: 400 }<br>                )<br>            }<br>        }<br><br>        // Generate the token<br>        const { token, validUntil } = generateEmbeddingToken({<br>            workspace_id,<br>            api_key_id,<br>            dashboard_id,<br>            validity_duration,<br>        })<br><br>        // Build iframe URL<br>        const baseUrl = process.env.NEXT_PUBLIC_APP_URL || &#39;https://papermap.ai&#39;<br>        const iframeParams = new URLSearchParams({<br>            &#39;embedded-token&#39;: token,<br>            &#39;workspace-id&#39;: workspace_id,<br>        })<br><br>        if (dashboard_id) {<br>            iframeParams.set(&#39;dashboard-id&#39;, dashboard_id)<br>        }<br><br>        const iframeUrl = `${baseUrl}/embedded/dashboard?${iframeParams.toString()}`<br><br>        return NextResponse.json({<br>            success: true,<br>            token,<br>            iframe_url: iframeUrl,<br>            expires_at: new Date(validUntil * 1000).toISOString(),<br>            valid_until: validUntil,<br>        })<br>    } catch (error) {<br>        console.error(&#39;Error generating embedding token:&#39;, error)<br>        return NextResponse.json(<br>            {<br>                error: &#39;Failed to generate embedding token&#39;,<br>                details: error instanceof Error ? error.message : &#39;Unknown error&#39;,<br>            },<br>            { status: 500 }<br>        )<br>    }<br>}<br><br><br><br></pre><p>This is a sample code to generate a token. Your payload should end up looking like this</p><pre>{<br>  &quot;workspace_id&quot;: &quot;&quot;,<br>  &quot;api_key_id&quot;: &quot;&quot;,<br>  &quot;dashboard_id&quot;: &quot;&quot;,<br>  &quot;validity_duration&quot;: 3600<br>}</pre><p>and your response should look like this. This is just an example so you can make it how ever you want.</p><pre>{<br>    &quot;success&quot;: true,<br>    &quot;token&quot;: &quot;eyJhcGlfa2V5X2lkIjoiYWtfMzJqV2psNldKYVFtR05XS2NraEthZyIsIndvcmtzcGFjZV9pZCI6IkJRTFRrdk5qTkJXUyIsInZhbGlkX3VudGlsIjoxNzY3NzY4OTUyLCJzaWduYXR1cmUiOiI4MDhhMDRhMDEyNTE4NDJiNGQwYjJiZTA5ZGEyNTc3ZTBkYTIxNzBhNjcwMjc0MzhlY2Y3MDY0M2JhNzYyNTA1IiwiZGFzaGJvYXJkX2lkIjoiZ0JVanNQdm5DV0RTQiJ9&quot;,<br>    &quot;iframe_url&quot;: &quot;https://papermap.ai/embedded/dashboard?embedded-token=eyJhcGlfa2V5X2lkIjoiYWtfMzJqV2psNldKYVFtR05XS2NraEthZyIsIndvcmtzcGFjZV9pZCI6IkJRTFRrdk5qTkJXUyIsInZhbGlkX3VudGlsIjoxNzY3NzY4OTUyLCJzaWduYXR1cmUiOiI4MDhhMDRhMDEyNTE4NDJiNGQwYjJiZTA5ZGEyNTc3ZTBkYTIxNzBhNjcwMjc0MzhlY2Y3MDY0M2JhNzYyNTA1IiwiZGFzaGJvYXJkX2lkIjoiZ0JVanNQdm5DV0RTQiJ9&amp;workspace-id=BQLTkvNjNBWS&amp;dashboard-id=gBUjsPvnCWDSB&quot;,<br>    &quot;expires_at&quot;: &quot;2026-01-07T06:55:52.000Z&quot;,<br>    &quot;valid_until&quot;: 1767768952<br>}</pre><p>After you are done, grab your iframe_url and embed it into your frontend like this</p><pre>&lt;iframe<br>        src=&quot;https://papermap.ai/embedded/dashboard?embedded-token=YOUR_EMBEDDED_TOKEN&amp;workspace-id=dIwIBPYdGmWS&amp;dashboard-id=specific-dashboard-id&amp;show-toolbar=true&amp;show-header=false&amp;show-nav=false&amp;show-dashboard-select=true&amp;chat-composer=false&amp;show-screenshot=true&amp;theme=dark&quot;<br>        width=&quot;100%&quot;<br>        height=&quot;100%&quot;<br>        frameborder=&quot;0&quot;<br>        allowfullscreen<br>      &gt;<br>      &lt;/iframe&gt;</pre><p>Papermap allows you to customize the embedded experience including toolbar visibility, AI chat controls, navigation, and theming.</p><p>You can explore all available configuration options here:<br>👉 <a href="https://docs.papermap.ai/documentation/embedding/configuration">https://docs.papermap.ai/documentation/embedding/configuration</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gNK_ZntcVWhpm6XLjXqIWw.png" /><figcaption>A music store analytic dashboard in darkmode</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k58NaWb1V-t9lxsMsnI0fg.png" /><figcaption>A music store dashboard in light mode</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jCZGGuNtWS2m8Dj5ZLToSA.png" /></figure><p>With this setup, you’re no longer just embedding charts; you are embedding an AI-powered analytics agent directly into your application.</p><p>Instead of hard-coding metrics or writing one-off queries, your users can explore data by asking questions in natural language without pulling developers into every conversation.</p><p>And that, for me, is the real win.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=10a4b7e309e4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Writing API Routein Nextjs14]]></title>
            <link>https://simeonnortey.medium.com/writing-api-routein-nextjs14-395dc40df27e?source=rss-cd2e550fbad7------2</link>
            <guid isPermaLink="false">https://medium.com/p/395dc40df27e</guid>
            <category><![CDATA[nextjs14]]></category>
            <category><![CDATA[nextjs-jwt]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[nextjs-authentication]]></category>
            <dc:creator><![CDATA[Simeon Nortey]]></dc:creator>
            <pubDate>Sat, 06 Jul 2024 20:16:40 GMT</pubDate>
            <atom:updated>2024-07-06T20:16:40.199Z</atom:updated>
            <content:encoded><![CDATA[<h3>Writing API Routes in Nextjs14</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*PJ87QhnDB4G5r6GynPSEVw.png" /></figure><p>As a software engineer, change can sometimes be challenging. I love using react in its raw form because I love having control over my project. Using Nextjs has taught me that it’s never about how you arrive at the solution but if you have the solution that works. If you are coming from a MERN stack or have a simple understanding of expressJS then this will be very easy for you. Okay so enough talk, let’s get started.</p><p>In creating a new NextJS application, just follow these instructions here on this page.</p><p><a href="https://nextjs.org/docs/getting-started/installation">Getting Started: Installation | Next.js</a></p><p>Great, now that we have set up our application, let’s create a simple authenticated application. let’s create a file named middleware.ts in the app folder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*Y6WULtU3XK5zN3zwzZ8FjQ.png" /></figure><p>In your middleware.ts let’s create a simple middleware.</p><pre>import { NextResponse } from &quot;next/server&quot;;<br>import type { NextRequest } from &quot;next/server&quot;;<br><br>export async function middleware(request: NextRequest) {<br>  return NextResponse.next();<br>}<br>export const config = {<br>  matcher: [<br>    &quot;/((?!_next/static|_next/image|favicon.ico|images|icons|scripts).*)&quot;,<br>  ],<br>};</pre><p>This is the middleware function that will run for every matched request. Currently, it just calls NextResponse.next(), which means the request will continue to the next handler without any modifications. All requests will go through.</p><p>Now, we will create our API folder under the app folder. So the API folder is going to keep all our routes. Your relative path should look like</p><p>src/app/api/login/route.ts</p><p>Now let&#39;s make sure our API is working. Copy the code below and paste it into the file.</p><pre>import { NextRequest, NextResponse } from &quot;next/server&quot;;<br><br>//req is short for request<br>export async function GET(req: NextRequest) {<br>  return NextResponse.json(<br>    { message: &quot;this is a get request&quot; },<br>    { status: 200 }<br>  );<br>}<br><br>export async function POST(req: NextRequest) {<br>  return NextResponse.json(<br>    { message: &quot;This is a post request&quot; },<br>    { status: 200 }<br>  );<br>}<br><br>export async function PATCH(req: NextRequest) {<br>  return NextResponse.json(<br>    { message: &quot;This is a patch request&quot; },<br>    { status: 200 }<br>  );<br>}<br>// you can also handle PATCH, DELETE, PUT</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/1*yE9J8XjLneFKZdBWpIzy1w.png" /><figcaption>Result for GET request on <a href="http://localhost/">http://localhost:</a>3000/api/login</figcaption></figure><p>For making request or testing requests, I like to use Postman or Curl. Now that is it. That is how to make an API in NextJS. Now let’s make this interesting and add an actual authentication route.</p><p><a href="https://www.postman.com/">Postman: The World&#39;s Leading API Platform | Sign Up for Free</a></p><p>Now outside our app folder, we can have our config folder where we can set up our database and whatnot for authentication. Now please note this, when it comes to authentication Nextjs has so many ways of handling this but in this article, I am going to go through one way of how you handle your authentication.</p><p>Since we are going to handle our own JWT (JSON Web Token), install jsonwebtoken</p><pre>npm install jsonwebtoken<br>#or <br>yarn add jsonwebtoken</pre><p>Add this to your configuration</p><pre>import jwt, { JwtPayload } from &quot;jsonwebtoken&quot;;<br>import { NextRequest } from &quot;next/server&quot;;<br><br>const JWT_SECRET = &quot;your_secret_key_goes_here&quot;;<br><br>export interface DecodeAccessToken extends JwtPayload {<br>  id?: string;<br>}<br><br>export const generateAccessToken = (userId: string) =&gt; {<br>  if (JWT_SECRET) {<br>    const tokenPayload = {<br>      userId,<br>      createdAt: Date.now(),<br>    };<br><br>    const accessToken = jwt.sign(tokenPayload, JWT_SECRET, {<br>      expiresIn: &quot;1h&quot;,<br>    });<br>    return accessToken;<br>  }<br>};<br><br>export const decodeAccessToken = (<br>  req: NextRequest<br>): DecodeAccessToken | null =&gt; {<br>  if (JWT_SECRET) {<br>    try {<br>      const access_token = req.nextUrl.searchParams.get(&quot;access_token&quot;);<br>      const authorization = req.headers.get(&quot;authorization&quot;);<br>      const accessToken = (access_token as string) || authorization || &quot;&quot;;<br>      const decodedToken = jwt.verify(<br>        accessToken,<br>        JWT_SECRET<br>      ) as DecodeAccessToken;<br>      return decodedToken;<br>    } catch (error) {<br>      return null;<br>    }<br>  }<br>  return null;<br>};</pre><p>Your token payload could be anything you want to encrypt. Normally we encrypt a user ID but don’t put sensitive data in there because these access_tokens can be unencrypted if your jwt_secret is known.</p><p>Now in your sign-in post request, we can have something like this. Please note that this is the bare minimum so you would have to handle all other aspects of your sign-in.</p><pre>import { signin } from &quot;@/config&quot;;<br>import { NextRequest, NextResponse } from &quot;next/server&quot;;<br><br>export async function POST(req: NextRequest) {<br>  try {<br>    const body = await req.json();<br>    const { email, password } = body;<br><br>    const accessToken = await signin({ email, password });<br><br>    return NextResponse.json(<br>      { message: &quot;login successful&quot;, accessToken },<br>      { status: 200 }<br>    );<br>  } catch (error) {<br>    console.log(&quot;error&quot;, error);<br>    return NextResponse.json({ message: &quot;error&quot; }, { status: 500 });<br>  }<br>}</pre><p>Now you can choose to handle the verification of the access_token either in the middleware or in the API route function. An example of how to handle your own middleware can be found below.</p><pre>import { decodeAccessToken } from &quot;@/config&quot;;<br>import { NextResponse } from &quot;next/server&quot;;<br>import type { NextRequest } from &quot;next/server&quot;;<br><br>const checkPath = (request: NextRequest) =&gt; {<br>  const authRoute = [&quot;/api/user&quot;, &quot;/api/members&quot;].includes(<br>    request.nextUrl.pathname<br>  );<br>  if (authRoute) {<br>    const isAuth = decodeAccessToken(request);<br>    if (!isAuth) {<br>      return NextResponse.json({ message: &quot;unauthorized&quot; }, { status: 401 });<br>    }<br>  }<br>  return NextResponse.next();<br>};<br><br>export async function middleware(request: NextRequest) {<br>  if (request.nextUrl.pathname.startsWith(&quot;/api&quot;)) {<br>    return checkPath(request);<br>  }<br>  return NextResponse.next();<br>}<br>export const config = {<br>  matcher: [<br>    &quot;/((?!_next/static|_next/image|favicon.ico|images|icons|scripts).*)&quot;,<br>  ],<br>};</pre><p>In the example above, We first check if the pathname starts with api . Then we also check if this route is authenticated. Now here is the thing, you can also do this in the route function itself. Again, it’s up to you. Do what works for you. You can have sub-middleware functions that handle different levels of authentication. I would always recommend to keep your middleware clean.</p><p>Another way of handling authentication is using NextAuth.js. You can read more about it here</p><p><a href="https://next-auth.js.org/">NextAuth.js</a></p><p>Writing APIs may not always be necessary, particularly if you do not need to interface with other applications. You may use the use serverdirective to handle server operations without writing APIs in NextJS. As I always say, make something awesome for you and your team. <a href="https://emojipedia.org/smiling-face-with-smiling-eyes">😊</a></p><p><a href="https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations">Data Fetching: Server Actions and Mutations | Next.js</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=395dc40df27e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to add multiple languages in React Native]]></title>
            <link>https://simeonnortey.medium.com/how-to-add-multiple-languages-in-react-native-43d27fc7e717?source=rss-cd2e550fbad7------2</link>
            <guid isPermaLink="false">https://medium.com/p/43d27fc7e717</guid>
            <category><![CDATA[i18n]]></category>
            <category><![CDATA[i18next]]></category>
            <category><![CDATA[multiple-language-app]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[react-i18next]]></category>
            <dc:creator><![CDATA[Simeon Nortey]]></dc:creator>
            <pubDate>Fri, 22 Sep 2023 09:36:01 GMT</pubDate>
            <atom:updated>2023-09-22T09:36:01.311Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*F17h5E8jiPdZk6vkLG1ZRg.gif" /></figure><p>There are two terms to consider when dealing with multiple languages in React Native and they are localization and internationalization. In the next two paragraphs, I talk about what they are but you can skip these two and get straight into the code.</p><p><strong>Internationalization(i18n) </strong><br>Internationalization, often abbreviated as “i18n” (where “18” represents the number of letters between “i” and “n” in the word), is the process of designing and developing software in a way that makes it easy to adapt for different languages, regions, and cultures. The goal of internationalization is to separate the application’s code from specific language and cultural elements. This involves abstracting text strings so they can be replaced or customized without changing the codebase.</p><p><strong>Localization(l10n)</strong><br>Localization, abbreviated as “L10n” (where “10” represents the number of letters between “L” and “n”), is the process of customizing and adapting a software application to a specific locale or region. This includes translating text, modifying date and time formats, and adjusting other culturally sensitive elements. The goal of localization is to make the software feel native to the users in a particular region or culture. This may involve translating user interface elements, modifying images or graphics, and ensuring that the software complies with local regulations and conventions.</p><p>Now, ask yourself, what is the difference🤔? Internationalization is the preparation phase that makes localization possible and efficient. Both processes are essential for creating software that can be effectively used and accepted by a global audience.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*6SFBQHo1lqKpxvOYAAdAwA.gif" /><figcaption>Joey from Friends trying to speak French</figcaption></figure><p>Okay enough talk, let&#39;s get started with the code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/384/1*RU2Gy5Gppn1AGpg9QViRSA.png" /></figure><p>After we create our React native project, let’s install the i18n plugins and react-native-async-storage</p><pre>npm install i18next react-i18next @react-native-async-storage/async-storage</pre><p>let’s create a folder called localization. You can call it whatever you want. Under your localization folder, create another folder called <strong>translations</strong> and a file <strong>i18n.ts</strong>.</p><p>let’s start with our translations. In the image above, we have two languages being used <strong>English</strong> and <strong>French. </strong>In your en.json file, define some of your text in JSON like this. Now you can create your structure in any way you want it and as you get further into it, you will understand. I like to structure texts in an order that can be read easily by other programmers. The example below shows that the language I am using is English, then I have screens, and other screens I have an intro screen, and so forth and so on.</p><pre>{<br>    &quot;language&quot;: &quot;English&quot;,<br>    &quot;screens&quot;: {<br>        &quot;intro&quot;: {<br>            &quot;title&quot;: &quot;Intro Screen&quot;,<br>            &quot;text&quot;: {<br>                &quot;introText&quot;: &quot;This is the intro text in english&quot;,<br>                &quot;login&quot;: &quot;Login&quot;,<br>                &quot;signup&quot;: &quot;Sign Up&quot;<br>            }<br>        },<br>        &quot;login&quot;: {<br>            &quot;title&quot;: &quot;Sign in&quot;,<br>            &quot;text&quot;: {<br>                &quot;login&quot;: &quot;login&quot;,<br>                &quot;emailAddress&quot;: &quot;Email address&quot;,<br>                &quot;password&quot;: &quot;password&quot;,<br>                &quot;continue&quot;: &quot;Continue&quot;,<br>                &quot;createAccount&quot;: &quot;Create an Account&quot;,<br>                &quot;forgotPassword&quot;: &quot;Forgotten password?&quot;<br>            }<br>        },<br>    }<br>}</pre><p>Okay, now let’s create the French file, fr.json.</p><pre>{<br>    &quot;language&quot;: &quot;French&quot;,<br>    &quot;screens&quot;: {<br>        &quot;intro&quot;: {<br>            &quot;title&quot;: &quot;Écran d&#39;introduction&quot;,<br>            &quot;text&quot;: {<br>                &quot;introText&quot;: &quot;voici le texte d&#39;introduction en français&quot;,<br>                &quot;login&quot;: &quot;Connexion&quot;,<br>                &quot;signup&quot;: &quot;S&#39;inscrire&quot;<br>            }<br>        },<br>        &quot;login&quot;: {<br>            &quot;title&quot;: &quot;S&#39;identifier&quot;,<br>            &quot;text&quot;: {<br>                &quot;login&quot;: &quot;connexion&quot;,<br>                &quot;emailAddress&quot;: &quot;Adresse e-mail&quot;,<br>                &quot;password&quot;: &quot;mot de passe&quot;,<br>                &quot;continue&quot;: &quot;Continuer&quot;,<br>                &quot;createAccount&quot;: &quot;Créer un compte&quot;,<br>                &quot;forgotPassword&quot;: &quot;Mot de passe oublié?&quot;<br>            }<br>        },<br>    }<br>}</pre><p>Now that we have our languages set up, let’s set up an index file to export them.</p><pre>export { default as en } from &quot;./en.json&quot;;<br>export { default as fr } from &quot;./fr.json&quot;;</pre><p>Now let’s set up our i18n file. Let me explain what the <strong>languageDetectorPlugin object does. </strong>This will run to check from your storage which language you last choose. It also caches the language in the storage. You can also add your own logic to detect the country of the user and select the language by default. You can remove the languagedetectorplugin object but if you do, your app will always revert to the fallback language.</p><pre>import i18n from &#39;i18next&#39;;<br>import { initReactI18next } from &#39;react-i18next&#39;;<br>import { en, fr } from &quot;./translations&quot;;<br>import AsyncStorage from &quot;@react-native-async-storage/async-storage&quot;;<br><br>const STORE_LANGUAGE_KEY = &quot;settings.lang&quot;;<br><br>const languageDetectorPlugin = {<br>    type: &quot;languageDetector&quot;,<br>    async: true,<br>    init: () =&gt; { },<br>    detect: async function (callback: (lang: string) =&gt; void) {<br>        try {<br>            // get stored language from Async storage<br>            // put your own language detection logic here<br>            await AsyncStorage.getItem(STORE_LANGUAGE_KEY).then((language) =&gt; {<br>                if (language) {<br>                    //if language was stored before, use this language in the app<br>                    return callback(language);<br>                } else {<br>                    //if language was not stored yet, use english<br>                    return callback(&quot;en&quot;);<br>                }<br>            });<br>        } catch (error) {<br>            console.log(&quot;Error reading language&quot;, error);<br>        }<br>    },<br>    cacheUserLanguage: async function (language: string) {<br>        try {<br>            //save a user&#39;s language choice in Async storage<br>            await AsyncStorage.setItem(STORE_LANGUAGE_KEY, language);<br>        } catch (error) { }<br>    },<br>};<br>const resources = {<br>    en: {<br>        translation: en,<br>    },<br>    fr: {<br>        translation: fr,<br>    },<br>};<br><br>i18n.use(initReactI18next).use(languageDetectorPlugin).init({<br>    resources,<br>    compatibilityJSON: &#39;v3&#39;,<br>    // fallback language is set to english<br>    fallbackLng: &quot;en&quot;,<br>    interpolation: {<br>        escapeValue: false,<br>    },<br>});<br>export default i18n;</pre><p>In your main file like <strong>App.tsx</strong>, import the i18n file</p><figure><img alt="import 18n.js" src="https://cdn-images-1.medium.com/max/1024/1*4scUVX-rYdhyMxYZUaHQrA.png" /></figure><p>Great, now we can start using our i18n setup. Let’s create our screens, say login screen or IntroStreen. I have an example below. This uses Nativebase for my UI but you can just ignore that. Get the t function from the useTranslation hook from react-i18next and pass a string indicating what text to display.<br>For example, <strong>t(“screens.intro.text.introText”)</strong> will translate to <strong>This is the intro text in English.</strong></p><p><strong>NOTE</strong> how the text is arranged on how the object is defined in the language.</p><pre>import React from &#39;react&#39;;<br>import { Box, Flex, HStack, Image, Stack, Text, VStack } from &#39;native-base&#39;;<br>import { Button, Heading } from &#39;../../components/ui&#39;;<br>import { RouteNames } from &#39;../../constants&#39;;<br>import { useTranslation } from &#39;react-i18next&#39;;<br><br>function IntroSliderScreen({ navigation }) {<br>  const { t } = useTranslation();<br>  return (<br>   <br>      &lt;VStack flex=&quot;1&quot;&gt;<br>        &lt;Box flex=&quot;0.5&quot;&gt;<br>          &lt;Stack justifyContent=&quot;center&quot; bg=&quot;brand.200&quot; h=&quot;100%&quot; borderTopRadius=&quot;24&quot; px={10}&gt;<br>            &lt;VStack space={6}&gt;<br>              &lt;Box&gt;<br>                &lt;Heading fontSize={24} textAlign=&quot;center&quot;&gt;<br>                  {t(&quot;screens.intro.text.introText&quot;)}<br>                &lt;/Heading&gt;<br>              &lt;/Box&gt;<br>              &lt;Box w=&quot;100%&quot; alignItems=&quot;center&quot;&gt;<br>                &lt;HStack w=&quot;100%&quot; space={3} alignItems=&quot;center&quot;&gt;<br>                  &lt;Button<br>                    flex={0.5}<br>                    variant=&quot;secondary&quot;<br>                    onPress={() =&gt; navigation.navigate({ name: RouteNames.LOGIN })}<br>                  &gt;<br>                    &lt;Text&gt;{t(&quot;screens.intro.text.login&quot;)}&lt;/Text&gt;<br>                  &lt;/Button&gt;<br>                  &lt;Button<br>                    flex={0.5}<br>                    onPress={() =&gt; navigation.navigate({ name: RouteNames.REGISTER })}<br>                  &gt;<br>                    {t(&quot;screens.intro.text.signup&quot;)}<br>                  &lt;/Button&gt;<br>                &lt;/HStack&gt;<br>              &lt;/Box&gt;<br>            &lt;/VStack&gt;<br>          &lt;/Stack&gt;<br>        &lt;/Box&gt;<br>      &lt;/VStack&gt;<br>  );<br>}<br><br>export { IntroSliderScreen };</pre><p>Now you might be wondering, how do I get this to change to French? Pretty simple. You can use the i18n function to change the language. Example below.</p><pre>import { useTranslation } from &#39;react-i18next&#39;;<br><br>function LanguageScreen() {<br> const { t, i18n } = useTranslation(); //i18n instance<br>  return (<br>    &lt;View&gt;<br>      &lt;TouchableOpacity onPress={() =&gt; i18n.changeLanguage(&quot;en&quot;)}&gt;<br>        &lt;Text&gt;English&lt;/Text&gt;<br>      &lt;/TouchableOpacity&gt;<br>      &lt;TouchableOpacity onPress={() =&gt; i18n.changeLanguage(&quot;fr&quot;)}&gt;<br>        &lt;Text&gt;French&lt;/Text&gt;<br>      &lt;/TouchableOpacity&gt;<br>    &lt;/View&gt;<br>  )<br>}</pre><p>Now, this is a simple snippet of how to change the language but I encourage you to tinker with the code and create something amazing.</p><p>Happy hacking!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=43d27fc7e717" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to duotone or add filter effect on images with Javascript]]></title>
            <link>https://simeonnortey.medium.com/how-to-duotone-or-add-filter-effect-on-images-with-javascript-7007836566f?source=rss-cd2e550fbad7------2</link>
            <guid isPermaLink="false">https://medium.com/p/7007836566f</guid>
            <category><![CDATA[duotone]]></category>
            <category><![CDATA[filters]]></category>
            <category><![CDATA[nuxtjs]]></category>
            <category><![CDATA[vue]]></category>
            <dc:creator><![CDATA[Simeon Nortey]]></dc:creator>
            <pubDate>Thu, 20 Apr 2023 22:39:28 GMT</pubDate>
            <atom:updated>2023-04-22T14:07:08.858Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*92YhLKfhpx2yyVFPOqmLbw.png" /><figcaption>D<a href="https://duotonemaker.netlify.app/">uotonemaker</a></figcaption></figure><p>Duotone is a popular image effect in web design that involves using two colours to create a striking, high-contrast image. In this article, we’ll explore how to achieve this effect using JavaScript.</p><p>I created this web application with <a href="https://github.com/AndyOsei">Andy Osei</a> and <a href="https://elikemdaniels.com/">Elikem Daniels</a> to help designers duotone or add filters to images but for those who actually want to know how this is done, this is for you.</p><p>In this article I am not going to go into the API works no, but I will talk about how to get the images to change colours as soon as users change image colour. let’s get into the code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/448/1*BdMhAwH8CeqzuMM07jibAQ.gif" /></figure><h3>Applying duotone on image in SVG</h3><p>I wrote this application using Vuejs but I am more of a React guy. Whichever way you go, it will work for you. First thing is first, what image are we filtering? let&#39;s say we want to duotone the image below by <a href="https://unsplash.com/@f_abrarrr?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Fathul Abrar</a> on <a href="https://unsplash.com/images/food?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a>. The food looks good, ok now I am hungry.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xrGtFb9M-l6BJLPWjIAmfg.jpeg" /></figure><p>We will need to get the image link or the source of the image. The trick is a simple one. Embed the image inside and SVG and manipulate the feColorMatrix. That&#39;s all, the image has been duotoned. Now let’s look at the code that makes this alive.</p><pre>&lt;svg<br>  xmlns:xlink=&quot;http://www.w3.org/1999/xlink&quot;<br>  :viewBox=&quot;`0 0 ${image_width} ${image_height}`&quot;<br>&gt;<br>  &lt;filter id=&quot;duotone&quot;&gt;<br>    &lt;feColorMatrix<br>      type=&quot;matrix&quot;<br>      values=&quot;&quot;<br>      color-interpolation-filters=&quot;sRGB&quot;<br>    /&gt;<br>  &lt;/filter&gt;<br>  &lt;image<br>    width=&quot;100%&quot;<br>    height=&quot;100%&quot;<br>    filter=&quot;url(#duotone)&quot;<br>    xlink:href=&quot;https://images.unsplash.com/photo-1586511925558-a4c6376fe65f?ixlib=rb-4.0.3&amp;ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&amp;auto=format&amp;fit=crop&amp;w=774&amp;q=80&quot;<br>    x=&quot;0&quot;<br>    y=&quot;0&quot;<br>    preserveAspectRatio=&quot;xMidYMid slice&quot;<br>  /&gt;<br>&lt;/svg&gt;</pre><p>Now the real work begins. You see we need to get the color matrix of the two colours you want to duotone. it might look like <br>“0.27734375 0 0 0 0.28515625 0.82421875 0 0 0 0.05078125 0.58984375 0 0 0 0.34375 0 0 0 1 0”</p><p>Guys, what in the world is this 🤨</p><pre>&lt;feColorMatrix data-v-2c672f1f=&quot;&quot; type=&quot;matrix&quot; values=&quot;0.27734375 0 0 0 0.28515625 0.82421875 0 0 0 0.05078125 0.58984375 0 0 0 0.34375 0 0 0 1 0&quot; color-interpolation-filters=&quot;sRGB&quot;&gt;&lt;/feColorMatrix&gt;</pre><p>But fear not, for there is a function to save us from this nightmare.</p><pre>export const hexToRgb = (hex) =&gt; {<br>  const normal = hex.match(/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i);<br>  if (normal) {<br>    return normal.slice(1).map((e) =&gt; parseInt(e, 16));<br>  }<br><br>  const shorthand = hex.match(/^#([0-9a-f])([0-9a-f])([0-9a-f])$/i);<br>  if (shorthand) {<br>    return shorthand.slice(1).map((e) =&gt; 0x11 * parseInt(e, 16));<br>  }<br><br>  return null;<br>};<br><br>export const getPrimaryAndSecondaryColors = ({<br>  firstColor,<br>  secondColor,<br>  primaryColor,<br>}) =&gt; {<br>  let colors = [firstColor, secondColor];<br>  colors = colors.filter((color) =&gt; color !== primaryColor);<br>  return { primaryColor, secondaryColor: colors[0] };<br>};<br><br>export const duotoneImage = ({<br>  selector = &quot;feColorMatrix&quot;,<br>  firstColor,<br>  secondColor,<br>  primaryColor,<br>}) =&gt; {<br>  const matrix = document.querySelectorAll(selector);<br>  let value = [];<br>  const colors = getPrimaryAndSecondaryColors({<br>    firstColor,<br>    secondColor,<br>    primaryColor,<br>  });<br>  let color1 = hexToRgb(colors.primaryColor);<br>  let color2 = hexToRgb(colors.secondaryColor);<br>  value = value.concat([<br>    color1[0] / 256 - color2[0] / 256,<br>    0,<br>    0,<br>    0,<br>    color2[0] / 256,<br>  ]);<br>  value = value.concat([<br>    color1[1] / 256 - color2[1] / 256,<br>    0,<br>    0,<br>    0,<br>    color2[1] / 256,<br>  ]);<br>  value = value.concat([<br>    color1[2] / 256 - color2[2] / 256,<br>    0,<br>    0,<br>    0,<br>    color2[2] / 256,<br>  ]);<br>  value = value.concat([0, 0, 0, 1, 0]);<br>  matrix.forEach((m) =&gt; {<br>    m.setAttribute(&quot;values&quot;, value.join(&quot; &quot;));<br>  });<br>};</pre><p>The duotoneImage function works its magic and we are done. I am just kidding, let me explain. It’s taking in an object parameter having a “selector” which in this case is feColorMatrix, you could have more svgs in your HTML with different ids. It’s up to you to manipulate or pass your own selector. The “firstColor” is the first colour of your duotone, remember, duotone works with 2 colours and you have to choose which one of the colours would be a primary colour. The second part of the function is not so important if you don’t want to manipulate primary and secondary colours you can always use your first colour to default as a primary colour. After that, we create the colour matrix by doing some magic maths which you can ask ChatGPT later 😄 . For the last part, we set the attribute value of the selector to the Color Matrix and boom, the image is duotoned.</p><h3><strong>Downloading The SVG</strong></h3><p>If you have made it this far, you are awesome. Let’s get into it</p><pre>async downloadImage() {<br>      <br>      const base64 = await this.getBase64FromUrl(img_link_goes_here);<br>      this.imgSrc = base64;<br>      const filter = document.querySelector(&quot;#duotone&quot;).outerHTML;<br>      const svg = `&lt;svg version=&quot;1.1&quot; id=&quot;Layer_1&quot; xmlns=&quot;http://www.w3.org/2000/svg&quot; xmlns:xlink=&quot;http://www.w3.org/1999/xlink&quot; x=&quot;0px&quot; y=&quot;0px&quot;<br>   width=&quot;${this.img.width}&quot; height=&quot;${this.img.height}&quot;<br>   xml:space=&quot;preserve&quot; viewBox=&quot;0 0 ${this.img.width} ${this.img.height}&quot;&gt;<br>   ${filter}&lt;image width=&quot;100%&quot; height=&quot;100%&quot; filter=&quot;url(#duotone)&quot; href=&quot;${base64}&quot; x=&quot;0&quot; y=&quot;0&quot; preserveAspectRatio=&quot;xMidYMid slice&quot; &gt;&lt;/image&gt;&lt;/svg&gt;<br>   `;<br>      this.downloadSVGAsPNG(svg, this.img.height, this.img.width, loading);<br>},</pre><p>This part is a little tricky because we can’t just download the SVG directly just like that. If you try to download the SVG directly you will notice that the image will be broken due to the fact that the image is a link. We need to encode the image in base64 and embed it into the SVG before downloading it. The loading param is just to set the loading state and can be ignored.</p><pre>// GET base64 of image<br> async getBase64FromUrl(url) {<br>      if (!this.img.custom) {<br>        const data = await fetch(url);<br>        const blob = await data.blob();<br>        return new Promise((resolve) =&gt; {<br>          const reader = new FileReader();<br>          reader.readAsDataURL(blob);<br>          reader.onloadend = () =&gt; {<br>            const base64data = reader.result;<br>            resolve(base64data);<br>          };<br>        });<br>      }<br>      if (this.img.custom) {<br>        return new Promise((resolve) =&gt; {<br>          const reader = new FileReader();<br>          reader.readAsDataURL(this.img.file);<br>          reader.onloadend = () =&gt; {<br>            const base64data = reader.result;<br>            resolve(base64data);<br>          };<br>        });<br>      }<br>   },</pre><pre>downloadSVGAsPNG(payload, height, width, loading) {<br>      const canvas = document.createElement(&quot;canvas&quot;);<br>      const base64doc = btoa(unescape(encodeURIComponent(payload)));<br>      const w = parseInt(width);<br>      const h = parseInt(height);<br>      const img_to_download = document.createElement(&quot;img&quot;);<br>      img_to_download.src = &quot;data:image/svg+xml;base64,&quot; + base64doc;<br><br>      img_to_download.onload = function () {<br>        canvas.setAttribute(&quot;width&quot;, w);<br>        canvas.setAttribute(&quot;height&quot;, h);<br>        const context = canvas.getContext(&quot;2d&quot;);<br>        context.clearRect(0, 0, w, h);<br>        context.drawImage(img_to_download, 0, 0, w, h);<br>        const dataURL = canvas.toDataURL(&quot;image/png&quot;);<br>        loading.close();<br>        if (window.navigator.msSaveBlob) {<br>          window.navigator.msSaveBlob(canvas.msToBlob(), &quot;download.png&quot;);<br>          this.loading = false;<br>        } else {<br>          const a = document.createElement(&quot;a&quot;);<br>          const my_evt = new MouseEvent(&quot;click&quot;);<br>          a.download = &quot;download.png&quot;;<br>          a.href = dataURL;<br>          a.dispatchEvent(my_evt);<br>        }<br>        canvas?.parentNode?.removeChild(canvas);<br>      };<br>      img_to_download.onerror = function (error) {<br>        console.log(error);<br>      };<br>    },</pre><p>It is important to give the SVG a width and a height as it can’t default to its original width and height.<br>I am leaving a link to the project on GitHub (<a href="https://github.com/Leleking/duotonemaker">https://github.com/Leleking/duotonemaker</a>) so you can check it out and do something awesome with it. I will be adding more functionalities to Duotonemaker and I am open to collaborators. Happy coding.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7007836566f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How To Structure Folders In Your React Application]]></title>
            <link>https://simeonnortey.medium.com/how-to-structure-folders-in-your-react-application-567ddad3bd7e?source=rss-cd2e550fbad7------2</link>
            <guid isPermaLink="false">https://medium.com/p/567ddad3bd7e</guid>
            <category><![CDATA[reactive-programming]]></category>
            <category><![CDATA[how-to]]></category>
            <category><![CDATA[folder-structure]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Simeon Nortey]]></dc:creator>
            <pubDate>Thu, 20 Apr 2023 07:36:51 GMT</pubDate>
            <atom:updated>2023-04-20T07:36:51.423Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DNN5mP3VUVQIOmRDInn8gA.jpeg" /></figure><p>I have always loved to have full control over everything I build but starting out with something new is sometimes tedious. You really don’t know what to do so you end up looking online to find so many possibilities and sometimes it is just so confusing. In this article, I want to share with you some of the patterns I picked up while creating React applications.</p><p>Folder structures for frontend frameworks are endless. It’s not like some backend framework like Laravel or Django or nestJS that follow a certain pattern no no no, you are left with this below and you have to come up with your own structure.</p><figure><img alt="React application with typescript" src="https://cdn-images-1.medium.com/max/452/1*9Z-j4hPQPnyfHCwGhxQvAQ.png" /></figure><p>Ok let’s just jump right in</p><p><strong>Components — </strong>The components folder well as the name goes is where you keep all your components. I am assuming you know what components are if you don’t then take a step back with some good old <a href="https://reactjs.org/docs/getting-started.html">Documentation</a>. Yes, I am going to give you an example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/1*n9GQj-_HYWFQz0ep6DgrgA.png" /></figure><p>Layout — The layout folder, this folder is going to contain the layouts of our application. What do I mean when I say this? Imagine you have an application that has a landing page, authentication pages, dashboard pages, error pages, and so on, These groups of pages would have a similar layout to themselves. The dashboard layout could have a sidebar and a navbar whiles error pages like 404 would not have this. To make use of reusable components, we can put these layouts into the layout folder</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/1*2b2DP39gaAzWPcbzHzGN4w.png" /></figure><p>Example Layout code <a href="https://ray.so/?title=&amp;theme=breeze&amp;spacing=16&amp;background=true&amp;darkMode=true&amp;code=aW1wb3J0IHsgQm94IH0gZnJvbSAiQGNoYWtyYS11aS9yZWFjdCI7CmltcG9ydCBSZWFjdCwgeyBSZWFjdE5vZGUgfSBmcm9tICJyZWFjdCI7CmltcG9ydCBTaWRlYmFyIGZyb20gIi4uL2NvbXBvbmVudHMvU2lkZU5hdiI7CmV4cG9ydCBkZWZhdWx0IGZ1bmN0aW9uIERhc2hib2FyZExheW91dCh7IGNoaWxkcmVuIH06IHsgY2hpbGRyZW46IFJlYWN0Tm9kZSB9KSB7CiAgcmV0dXJuICgKICAgIDxTaWRlYmFyPgogICAgICA8Qm94IG10PXs0fT57Y2hpbGRyZW59PC9Cb3g-CiAgICA8L1NpZGViYXI-CiAgKTsKfQo&amp;language=javascript">here</a> using <a href="https://chakra-ui.com/">Chakra-ui</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lDE8wVifnKiv1rIPatvm-Q.png" /></figure><pre>import { DashboardLayout } from &quot;../../layout&quot;;</pre><pre>export default function Home() {</pre><pre>return (<br>      &lt;DashboardLayout&gt;<br>       &lt;div&gt;home page&lt;/div&gt;</pre><pre>      &lt;/DashboardLayout&gt;;</pre><pre>}</pre><p>There are other ways you could do this, you could handle some authentication somewhere in the application and switch layouts depending on what to show but that is for another article. Sometimes, simplicity is the key.</p><p><strong>Pages/ Views — </strong>This folder is going to hold your views or your pages. So in the image below, you can see that I have 3 folders under pages. You don’t have to have folders if your application is a small app. Let me give you a scenario for folders and one which would not need folders in my pages folder.<br>Scenario 1. Building a simple Landing page with say 3 pages, /, /contact, /team<br>These will require only 3 files give or take, emphasis on simple guys</p><ul><li>home.tsx / home.js</li><li>contact.tsx / contact.js</li><li>team.tsx / team.js</li></ul><p>Scenario 2. Building with multiple pages like say an e-commerce app.</p><ul><li>Products — in this folder we could have products, ProductsView, etc.</li></ul><p>This helps you to group your pages easily. Remember, a page is a component so you can have some components that are maybe unique to products in the products folder and that is that.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/368/1*Zzfqd3nqTgvuFoKqiX8qpw.png" /></figure><p>Router — We can’t talk about folder structure without the router folder. Used for routing. I am only going to show the folder structure for routing and wouldn’t go deeper into this but I will share a GitHub repository at the end of the article to show you how to get it all connected. We could have all router-related configurations in this folder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/368/1*XxklVW4km6egSUrgDZkjOA.png" /></figure><p><a href="https://v5.reactrouter.com/web/guides/quick-start">React Router: Declarative Routing for React</a></p><p>Services — The services folder should hold all API call functions. There are many ways to go about this too. In the services folder, you can have an index.ts where you configure your axios instance and export all other services.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/368/1*nWaHkOFqfeIlEqcTMN6jkQ.png" /></figure><p>Store — The store folder is going to hold you guessed it, global state management files. Now you could be using <a href="https://react-redux.js.org/">redux</a>, <a href="https://github.com/pmndrs/zustand">zustand</a> or <a href="https://github.com/CharlesStover/reactn">reactn</a> it doesn’t matter, the store can hold all this for you. <em>(picture below is using zustand)</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/414/1*TEh3peXO7yXLrWFljtaJXw.png" /></figure><p>Types — This option only applies to my Typescript lovers, a folder to keep all your types and interfaces. I would recommend having types separated from your components as it reduces complexity in the code and really makes your work easy when writing tests</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/414/1*vj_Bo99H6_yIZG5CMiEzpg.png" /></figure><p>Utils — The utils folder is short for the utility folder. You see those functions you use all the time and don’t want to repeat them throughout your application, well this is where they go. In the folder below you can see errorHandler.ts, this file can contain functions to handle errors. Let’s take a look at the function handleAPIError(). The first section always checks if the app environment is not in production before it logs errors. This simple code can prevent your app from logging errors that are not for users to see in production. It also has a displayError Parameter which you can pass a boolean state of true to intentionally log errors. Another important thing is that it is getting the error message and returning it. I really do not have the time to repeat this throughout the application so this is one of the best ways to handle it. You can build your error handlers to incoperate other functionalities like navigate to 500 page when there is a server error and so on.</p><pre>//example<br>export const handleAPIError = (error:any, displayError = false) =&gt; {</pre><pre> if (process.env.NODE_ENV !== &quot;production&quot;) {</pre><pre>  console.log(error);</pre><pre> }</pre><pre> if (error &amp;&amp;Object.getOwnPropertyNames(error).includes(&quot;response&quot;))   {</pre><pre> const message = error?.response?.data?.message;</pre><pre>if (displayError) {</pre><pre> console.log(&quot;message&quot;, message)</pre><pre>}</pre><pre>return message</pre><pre>}</pre><pre>};</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/414/1*lxrHVPD7c_rDl3PQzbd0Ag.png" /></figure><p>Hooks — If you know about react hooks then you probably know about react custom hooks. This is the folder to keep your custom hooks</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/446/1*9Tbb0eAeOBVs7mI79svPYQ.png" /></figure><p>Sometimes you want to see how it all comes about, so I have created a GitHub project with a simple react-folder-structure. <a href="https://github.com/Leleking/react-folder-structure">https://github.com/Leleking/react-folder-structure</a><br>NB: this project is just to show how the folder structure looks like and to elaborate the router configuration.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=567ddad3bd7e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How To Structure Folders In Your Vue Application]]></title>
            <link>https://simeonnortey.medium.com/how-to-structure-folders-in-your-vue-application-ea3934d56380?source=rss-cd2e550fbad7------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea3934d56380</guid>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[structure]]></category>
            <dc:creator><![CDATA[Simeon Nortey]]></dc:creator>
            <pubDate>Thu, 20 May 2021 01:27:05 GMT</pubDate>
            <atom:updated>2021-05-20T01:49:40.050Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vj-6rx5pN8aoQcbs_z0CKw.jpeg" /></figure><p>Getting started in <a href="https://vuejs.org/v2/guide/">vue.js</a> is pretty easy and very straight forward but just like any other frontend framework, you are left with the question, how do I structure my folders? Well, there is no wrong answer to this but there is an answer that can make your experience with Vue super easy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*kpdbywPuV67g-Gp7fA5yDQ.png" /></figure><p>In this article, I am going to talk about the folder structure in your src folder. We are not going to necessarily use all these folders but it’s good to have the knowledge on how everything is connected. let’s dive in</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*dXtTzUT4MHPndSvDufscrQ.jpeg" /></figure><p><strong>Assets</strong> — The assets folder holds your asset files like CSS files, fonts and images.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/224/1*tSKVuJa31a1mRN7n1FODmQ.png" /><figcaption>Assets folder structure</figcaption></figure><p><strong>Components</strong> — The components folder holds all reusable components of the application <strong>N.B</strong>. the components folder will not hold views but rather only reusable components. We are going to divide the Components folder into 2 or more depending on what exactly you will need</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/211/1*ehQ2g0qCJtusq4JPw9S4wg.png" /><figcaption>Components Folder</figcaption></figure><p>Notice I have 2 subfolders and other files in my components folder. My widgets folder contains all widget components. These are simple components like profile and small widget graphs. Again, it is not necessary at all but it is just an example of how you can group your components in the <strong>Components folder. </strong>Now, the Global folder is going to be used to register components throughout the application. Yes. components we put in the Global folder will not need to be imported into any file. Pretty cool right, yes, Vue is awesome 😎.</p><p><a href="https://vuejs.org/v2/guide/components-registration.html#Automatic-Global-Registration-of-Base-Components">Component Registration - Vue.js</a></p><p>I am going to explain how it works but you can also read about it in the Vue documentation. I know I skipped this the first time I studied vue. You might be wondering, what should I put in the Global component then, well just put your simple components that don’t take long to load. An example, a button, or a custom input. I am also using the word “Base” as a starting name for my components to differentiate them as custom components and also to be able to handpick them by the word Base</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/211/1*evXoQmp4WhyWOFVij3aImQ.png" /><figcaption>Global Folder</figcaption></figure><p><strong>Design</strong> — This can hold your SCSS files. this folder is not really necessary but good for those devs out there who like to keep everything clean as possible so if you are not a fan of SCSS then don’t worry about the design folder.</p><p><strong>Helpers</strong> — As the name suggests, the helpers will hold helper functions that you would like to use in your application. An example of these files is one that I have here called the errorhandler. These contain functions used to handle errors in the application. You can also use the helpers folder to hold other things like dummy data and so on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/211/1*UwiQFBcs7kCvBrMgo5kS3w.png" /><figcaption>Helpers Folder</figcaption></figure><p><strong>Layouts</strong> — The layouts folder is used to hold the layouts of your application. An example of a layout is <strong>AuthLayout.vue. For </strong>example,</p><pre>&lt;template&gt;<br>   &lt;div&gt;<br>     &lt;div&gt;This Screen is used for authentication&lt;/div&gt;<br>     &lt;router-view&gt;&lt;/router-view&gt;<br>   &lt;/div&gt;<br>&lt;/template&gt;</pre><p>i can load both my login or registration file on file. This is using the concept of <a href="https://router.vuejs.org/guide/essentials/nested-routes.html">nested vue routes</a>.</p><p><strong>Locales</strong> — This is the folder that I rarely use. I got the concept from another project which had to configure many languages for the application. All language configurations go here</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/211/1*XFuCRyb0_m4IWl6TMy_K1Q.png" /><figcaption>Locals Folder</figcaption></figure><p><strong>Router</strong> — This folder contains all router configurations and routes</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/211/1*8P-lIku0KslDNQjYAoSVMw.png" /><figcaption>Router folder</figcaption></figure><pre>//example routes file<br>export default [<br>  {<br>     path: &#39;/&#39;,<br>     name: &#39;welcome&#39;,<br>     component: () =&gt; import(&#39;../views/welcome&#39;)<br>   },<br>   {<br>     path: &#39;/about&#39;,<br>     name: &#39;about&#39;,<br>     component: () =&gt; import(&#39;../views/about&#39;)<br>   }</pre><pre>]</pre><p>the routes file will hold all your routes and the index.js file in the router folder can hold your router configuration.</p><pre>//exmple index.js in router folder<br><em>import</em> Vue <em>from</em> &#39;vue&#39;</pre><pre><em>import</em> VueRouter <em>from</em> &#39;vue-router&#39;</pre><pre><em>import</em> routes <em>from</em> &#39;./routes&#39;</pre><pre>const router = new VueRouter({<br>routes,<br>mode: &#39;history&#39;<br>})</pre><pre>export default router</pre><p>You can later import the router into main.js and register it there. See, pretty easy right.☺️</p><p><strong>Services</strong> — the services folder holds all API call functions</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/211/1*3KEwe6Rg0AAtNlQDwoNY9g.png" /><figcaption>Services folder</figcaption></figure><p>the <a href="https://www.npmjs.com/package/axios">Axios</a> folder here contains <a href="https://www.npmjs.com/package/axios">Axios</a> configuration.</p><pre>//axios configuration</pre><pre><em>import</em> Axios <em>from</em> &#39;axios&#39;</pre><pre>const instance  =  Axios.create({</pre><pre>baseURL: process.env.VUE_APP_API_DOMAIN,</pre><pre>responseType: &#39;json&#39;,</pre><pre>timeout: 20000</pre><pre>})</pre><pre>const axios = instance;</pre><pre>export { axios }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/258/1*dhopC2JZXce1jhXuaqWIZA.png" /></figure><p>The modules folder contains all your services. An example of this service is the AuthService. This file contains all API calls that have to do with authentication.</p><pre><em>import</em> {axios} <em>from</em> &#39;../axios&#39;</pre><pre><em>/**<br>*<br>* @param {Object} payload<br>*<br>* get access token<br>*/</em></pre><pre><em>export</em> const signIn = (payload) =&gt; {<br>   <em>return</em> axios.post(&#39;login &#39;,payload)<br>   .then(({data}) =&gt; {<br>        <em>return</em> Promise.resolve(data)<br>   })<br>   .catch((err) =&gt; {<br>       <em>return</em> Promise.reject(err)<br>   })</pre><pre>}</pre><p>I would encourage you to have this folder to make dealing with API calls easy. What is the benefit of separating your services? You can easily make changes to files using one API call.</p><p>the index.js file of the services can have the exports of the services</p><pre>//example<br>export * from &#39;./modules/AuthServices</pre><p>so you can import like</p><pre>import { signIn } from &#39;@/services&#39;</pre><p><strong>State</strong> — The state folder can also be called the store folder. It holds State management library configuration like <a href="https://vuex.vuejs.org/">Vuex</a> and its state modules</p><p>Utils — The utils folder holds plugin configurations, filters and GlobalComponent registration function. There is no need to write vue filters in every file. For example, you can write different filters and register them throughout the app. You can do anything you want here as the name gives, this is for utilities. You can even ignore the helpers folder and create a file in your utils that has your global functions. You can and should manipulate the folder structure to your convenience.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/258/1*WyiJLX81rgm3hSSfnFneYw.png" /></figure><pre>//register all components in Global folder</pre><pre><em>import</em> Vue <em>from</em> &#39;vue&#39;</pre><pre><em>import</em> _ <em>from</em> &#39;lodash&#39;</pre><pre>const requireComponent = require.context(&#39;@/components/Global&#39;,true,/[A-Z]\w+\.vue<em>$</em>/)</pre><pre>const getGlobalComponents = () =&gt; {</pre><pre>requireComponent.keys().forEach(fileName =&gt; {</pre><pre>const componentConfig = requireComponent(fileName)</pre><pre>const componentName = _.upperFirst(</pre><pre>_.camelCase(</pre><pre>fileName.split(&#39;/&#39;).pop().replace(/\.\w+<em>$</em>/, &#39;&#39;)</pre><pre>)</pre><pre>)</pre><pre>Vue.component(componentName,componentConfig.default || componentConfig)</pre><pre>})</pre><pre>}</pre><pre><em>export</em> <em>default</em> getGlobalComponents</pre><p>Now in the index.js in the utils folder</p><pre><em>import</em> GlobalComponents <em>from</em> &quot;./modules/GlobalComponents&quot;;</pre><pre>const utils = {<br>install(Vue, options){<br>GlobalComponents()</pre><pre>}}</pre><p>You can import this in your main.js and install it like</p><pre>//main.js<br>import utils from &#39;@/utils&quot;<br>Vue.use(utils)</pre><p><strong>Views</strong> — The views folder only holds your vue files like your login.vue etc.</p><p>There you have it guys, a cool folder structure you can use. You can also use</p><p>Assets, Components, Router, Services, State/Store, and Views alone. I encourage you to experiment with the structures and make something awesome for you and your team.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea3934d56380" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>