<?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 Enzo61 on Medium]]></title>
        <description><![CDATA[Stories by Enzo61 on Medium]]></description>
        <link>https://medium.com/@Enzo61?source=rss-a2d16f674ddd------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*cCmskFwHemrljIKQ3kFaRg.jpeg</url>
            <title>Stories by Enzo61 on Medium</title>
            <link>https://medium.com/@Enzo61?source=rss-a2d16f674ddd------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 16:30:50 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@Enzo61/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[POC of Firebase Hosting, Firestore, Firebase Cloud Functions with React and Express JS in 2025]]></title>
            <link>https://medium.com/@Enzo61/poc-of-firebase-hosting-firestore-firebase-cloud-functions-with-react-and-express-js-in-2025-dd214e582cac?source=rss-a2d16f674ddd------2</link>
            <guid isPermaLink="false">https://medium.com/p/dd214e582cac</guid>
            <category><![CDATA[firestore]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[firebase-cloud-functions]]></category>
            <category><![CDATA[firebase]]></category>
            <dc:creator><![CDATA[Enzo61]]></dc:creator>
            <pubDate>Wed, 05 Feb 2025 12:04:34 GMT</pubDate>
            <atom:updated>2025-02-05T12:04:34.196Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DIyMSGtZbDl58IO-zh-Z1g.png" /></figure><h3>Intro</h3><p>This is a very short tutorial about set up a React Web App and host it on Firebase Hosting, and then setup a Express JS backend and host it on Firebase Cloud Functions. Both the frontend and backend will be able to call Cloud Firestore.</p><p>Firebase Cloud Functions is a paid feature of Google, developer must use at least Blaze plan but not Free tier. However, useing emulator to run the Cloud Functions on local can be achieve in Free tier. In this tutorial, we will run the Cloud Functions and web app on Local, while Firestore online.</p><p>It consist of these steps:</p><p>Part1. Firebase Hosting<br>1. Setup project on firebase web console<br>2. Install Firebase CLI on laptop if haven’t<br>3. Create React project, init firebase, and deploy it to Firebase Hosting</p><p>Part2. Firestore<br>4. Setup Firestore and add some testing data<br>5. Install libraries, Add essential code to call firestore from React, deploy or run it on local.</p><p>Part3. Firebase Cloud Functions<br>6. Create a Express JS backend project, install required libraries and init<br>7. Add essential code to call firestore from backend and create api for web app to call<br>8. Run</p><h3>Part 1 — Firebase Hosting</h3><h4>1. Setup project on firebase web console:</h4><p>- Go to the Firebase console, add a new project.<br>- (Optional) Set up Google Analytics (we dont need in this POC)<br>- Click “Create project”.</p><h4>2. Install Firebase CLI on laptop if haven’t</h4><p>npm install -g firebase-tools<br>and login<br>firebase login<br>This will trigger a website in your browser for you to login.</p><h4>3. Create React project, init firebase, and deploy it to Firebase Hosting</h4><p>Let say if you use ‘create-react-app’ to create:<br>npx create-react-app project-name<br>Init firebase<br>firebase init<br><br>Choose ‘Hosting’ across the choices. ‘Hosting’ is for traditional web and web app so it fit our React web app. ‘App Hosting’ is for full-stack web app like Next.js.</p><p>Press Spacebar to select (you can multi-select), press enter to proceed.</p><p>If you want to, change your index page to a simple hello world. This is mine:</p><pre>function App() {<br>  return (<br>    &lt;div className=&quot;App flex-1 justify-center items-center&quot;&gt;<br>      &lt;p&gt;Hello Firebase Hosting&lt;/p&gt;<br>    &lt;/div&gt;<br>  );<br>}<br>export default App;</pre><p>Build your web app<br>npm run build<br>Then deploy<br>firebase deploy<br>This will deploy the contents of your `build` directory to your Firebase Hosting site. After the deployment is complete, the Firebase CLI will provide you with a Hosting URL (something like `<a href="https://your-project-id.web.app`/">https://your-project-id.web.app`</a>). Visit this URL in your browser to see your deployed React app</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4d3d-iLLmQ2owDE3Sgc_Qg.jpeg" /><figcaption>Firebase Hosting works</figcaption></figure><h3>Part 2 — Firestore</h3><h4>4. Setup Firestore and add some testing data</h4><p>Go firebase concole to setup a new Firestore database under .<br>Choose test mode so that it allows anyone to read and write to your database for 30 days. (Do not use test mode in production!)</p><p>Create a simple data structure like this:<br>- A collection called ‘testing’<br>- A document under ‘teting’ collection, with an auto ID and with data “content : HelloFirestore”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/947/1*h-3vJuVxEIQHE602Au676g.jpeg" /><figcaption>Firestore data</figcaption></figure><h4>5. Install libraries, Add essential code to call firestore from React, deploy or run it on local.</h4><p>To use Firestore, we need to install firebase to our project. Some AI will tell you to only install “<a href="http://twitter.com/firebase/firestore">@firebase/firestore</a>”. That doesn’t work, it will cause some bugs.</p><p>npm install firebase</p><p>We don’t need to `firebase init` and choose `Firestore` to use Firestore in our React project because we have already setup Firestore on web console.</p><p>Add essential code to React project to call the data from Firestore. Here we use a useEffect hook to fetch data and save it into useState, and display it in jsx. Normal operation.</p><pre>import &#39;./App.css&#39;;<br>import { useEffect, useState } from &#39;react&#39;;<br>import { getFirestore, doc, getDoc } from &quot;firebase/firestore&quot;;<br><br>function App({ app }) {<br>  const [firestoreContent, setFirestoreContent] = useState(null);<br>  const db = getFirestore(app)<br><br>  useEffect(() =&gt; {<br>    const fetchFirestoreData = async () =&gt; {<br>      try {<br>        const docRef = doc(db, &quot;testing&quot;, &quot;YOUR_DOC_ID&quot;);<br>        const docSnap = await getDoc(docRef);<br><br>        if (docSnap.exists()){<br>          setFirestoreContent(docSnap.data().content);<br>        } else {<br>          console.error(&quot;No such doc&quot;);<br>          setFirestoreContent(&quot;No such doc&quot;);<br>        }<br>      } catch(err) {<br>        console.error(&quot;Error fetching Firestore data:&quot;, err);<br>        setFirestoreContent(&quot;Error fetching data!&quot;);<br>      }<br>    }<br><br>    fetchFirestoreData();<br>  }, []);<br><br>  return (<br>    &lt;div className=&quot;App flex-1 justify-center items-center&quot;&gt;<br>      &lt;p&gt;Hello Firebase Hosting&lt;/p&gt;<br>      &lt;p&gt;{firestoreContent &amp;&amp; `From Firestore: ${firestoreContent}`}&lt;/p&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default App;</pre><p>You may now build and deploy it again to try, or just run it on local.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4vR676AMNRNe0LioF2BlBQ.png" /><figcaption>Show data from Firestore, Web App running on local</figcaption></figure><h3>Part3. Firebase Cloud Functions</h3><h4>6. Create a Express JS backend project, install required libraries and init</h4><p>Create an Express App</p><p>mkdir PROJECT-NAME<br>npm init -y<br>npm install express — save<br>npm install firebase-admin firebase-functions cors — save</p><p>firebase init<br>firebase init<br>Choose “Functions”, Select the existing project on firebase<br>(Do not choose Firestore here because we already setup on console)</p><h4>7. Add essential code to call firestore from backend and create api for web app to call</h4><p>We will create one mode doc in Firestore so that our frontend can show different strings and tell the data is through Cloud Functions.</p><p>Go to Firestore console, under ‘test’ collection, create another doc with auto id, add data “content2 : Hello Cloud Functions”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/951/1*S4vdCw0Vk0SIHdaa33nxnQ.jpeg" /><figcaption>Firestore data of doc2</figcaption></figure><p>Create an Express backend, here are some sample code, we are using Firebase Function V2 here. Endpoint is “/getContent”</p><pre>const {onRequest} = require(&quot;firebase-functions/v2/https&quot;);<br>const logger = require(&quot;firebase-functions/logger&quot;);<br>const express = require(&#39;express&#39;);<br>const cors = require(&#39;cors&#39;);<br>const admin = require(&#39;firebase-admin&#39;);<br><br>const app = express();<br><br>admin.initializeApp();<br><br>// my react app is running at localhost 3000<br>const allowedOrigins = [&#39;http://localhost:3000&#39;, &#39;http://127.0.0.1:3000/&#39;];<br><br>// for local test<br>app.use(cors({<br>  origin: function (origin, callback) {<br>    if (!origin || allowedOrigins.includes(origin)) {<br>      callback(null, true)<br>    } else {<br>      callback(new Error(&#39;Not allowed by CORS&#39;))<br>    }<br>  }<br>}));<br><br>app.get(&#39;/getContent&#39;, async (req, res) =&gt; {<br>  try {<br>    const db = admin.firestore();<br>    const docRef = db.collection(&#39;testing&#39;).doc(&#39;DOC2-ID&#39;);<br>    const doc = await docRef.get();<br><br>    if (!doc.exists) {<br>      return res.status(404).json({ error: &#39;Doc not found&#39;});<br>    }<br>    return res.json({ content: doc.data().content2 })<br>  } catch(err) {<br>    logger.error(&#39;Error:&#39;, err);<br>    console.error(&#39;Error:&#39;, err)<br>    return res.status(500).json({ error: &#39;Internal server error&#39;})<br>  }<br>});<br><br>exports.api = onRequest(app);</pre><p>Because of the limitation of the free tier, we will use emulator for this POC,</p><p>firebase emulators:start</p><p>After emulator successfully launched, you will see a line like <br>`http function initialized (<a href="http://127.0.0.1:5001/projectName-project-Id/region/api).%60">http://127.0.0.1:5001/projectName-project-Id/region/api).`</a> This is the endpoint we need to call in <br>our web app</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8sTFKyWKMa1lbhSKd6-RjQ.jpeg" /><figcaption>Cloud Function Emulator</figcaption></figure><p>Go to the React Project, add the endpoint and call it:</p><pre>import &#39;./App.css&#39;;<br>import { useEffect, useState } from &#39;react&#39;;<br>import { getFirestore, doc, getDoc } from &quot;firebase/firestore&quot;;<br>import { config } from &#39;./config&#39;;<br><br>function App({ app }) {<br>  const [firestoreContent, setFirestoreContent] = useState(null);<br>  const [backendContent, setBackendContent] = useState(null);<br>  const db = getFirestore(app)<br><br>  useEffect(() =&gt; {<br>    const fetchFirestoreData = async () =&gt; {<br>      try {<br>        const docRef = doc(db, &quot;testing&quot;, &quot;DOC1-ID&quot;);<br>        const docSnap = await getDoc(docRef);<br><br>        if (docSnap.exists()){<br>          setFirestoreContent(docSnap.data().content);<br>        } else {<br>          console.error(&quot;No such doc&quot;);<br>          setFirestoreContent(&quot;No such doc&quot;);<br>        }<br>      } catch(err) {<br>        console.error(&quot;Error fetching Firestore data:&quot;, err);<br>        setFirestoreContent(&quot;Error fetching data!&quot;);<br>      }<br>    }<br><br>    const fetchBackendData = async () =&gt; {<br>      try {<br>        console.log(`config: ${config.development.apiEndpoint}`)<br>        const response = await fetch(config.development.apiEndpoint);<br>        if (!response.ok) {<br>          console.error(`response not ok`);<br>        }<br>        const data = await response.json();<br>        setBackendContent(data.content);<br>      } catch (err) {<br>        console.error(&#39;error fetching from backend&#39;, err);<br>        setBackendContent(&quot;Error fetching from backend&quot;);<br>      }<br>    }<br><br>    fetchFirestoreData();<br>    fetchBackendData();<br>  }, []);<br><br>  return (<br>    &lt;div className=&quot;App flex-1 justify-center items-center&quot;&gt;<br>      &lt;p&gt;Hello Firebase Hosting&lt;/p&gt;<br>      &lt;p&gt;{firestoreContent &amp;&amp; `From Firestore: ${firestoreContent}`}&lt;/p&gt;<br>      &lt;p&gt;{backendContent &amp;&amp; `From Backend: ${backendContent}`}&lt;/p&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default App;<br></pre><pre>// config.js<br>// pls use dotenv in production<br>export const config = {<br>  development: {<br>    // Replace your own endpoint here, and remember to add &quot;/getContent&quot;<br>    apiEndpoint: &#39;http://127.0.0.1:5001/projectName-project-Id/region/api/getContent&#39;,<br>  }<br>}</pre><h4>8. Run</h4><p>Spin up your React web app too, now it should be able to show Hello World from the Web, From Firestore, and From Firestore through Cloud Funcitons</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RUiNpEhwejGaFzxaLUUVmw.jpeg" /><figcaption>Final Result</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dd214e582cac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Agora Voice Call SDK token uid issue]]></title>
            <link>https://medium.com/@Enzo61/agora-voice-call-sdk-token-uid-issue-28e42ae5b3bd?source=rss-a2d16f674ddd------2</link>
            <guid isPermaLink="false">https://medium.com/p/28e42ae5b3bd</guid>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[agora]]></category>
            <dc:creator><![CDATA[Enzo61]]></dc:creator>
            <pubDate>Sat, 21 Sep 2024 10:55:12 GMT</pubDate>
            <atom:updated>2025-02-05T12:06:53.639Z</atom:updated>
            <content:encoded><![CDATA[<h3>Background</h3><p>Agora is a voice call SDK that enable React Native app (and other platform) to perform voice call / video call.</p><p>Developer need to setup a token server with Agora library, and then:</p><ol><li>Generate token with (App id, App certificate, channel name, uid, role, token expire time)</li><li>Create channel with (token, channel name, uid)</li></ol><p><a href="https://docs.agora.io/en/signaling/get-started/authentication-workflow?platform=android">Signaling Secure authentication with tokens | Agora Docs</a></p><h3>Problem</h3><p>Create channel fail without meaningful erro log. Log I got is like:</p><ul><li>Error 100 (which just indicated token not valid)</li><li>Log of leaveing Channel right after log of joining channel</li><li>Log of attemp to join channel and no more</li></ul><h3>Cause</h3><p>uid for requesting Agora token must be of type number (int) and non 0.</p><p>Token server can still return rtc / rtm token with string uid, but that token can not be used to create channel, and without providing helpful error log.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=28e42ae5b3bd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[API call only fail on Android Emulator, but success on iOS simulator and Swagger]]></title>
            <link>https://medium.com/@Enzo61/api-call-only-fail-on-android-emulator-but-success-on-ios-simulator-and-swagger-6fb854037543?source=rss-a2d16f674ddd------2</link>
            <guid isPermaLink="false">https://medium.com/p/6fb854037543</guid>
            <category><![CDATA[react-native]]></category>
            <dc:creator><![CDATA[Enzo61]]></dc:creator>
            <pubDate>Wed, 18 Sep 2024 04:47:07 GMT</pubDate>
            <atom:updated>2024-09-18T04:47:07.748Z</atom:updated>
            <content:encoded><![CDATA[<h3>Problem description</h3><p>i have a react native expo project. It connect a dev server on ‘<a href="http://localhost:5001/api&#39;">http://localhost:5001/api&#39;</a>, when the server run, i can call the api on swagger, and also when the app run on ios simulator, but in android simulator, it returns error</p><pre> ERROR  Error in getAllSessionTypes: Network Error<br> ERROR  Failed to fetch upcoming sessions: Network Error</pre><p>i have tried to switch the localhost to my ipv4 address but it didn’t help, and switch to mobile hotspot didn’t help too</p><h3>Solution</h3><p>Instead of using ‘localhost’ or your IPv4 address, try using the special IP ‘10.0.2.2’. This IP is specifically used by Android emulators to access the host machine’s localhost. Change your API base URL to:</p><pre>http://10.0.2.2:5001/api</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6fb854037543" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using .env value in React Native Expo EAS build]]></title>
            <link>https://medium.com/@Enzo61/using-env-value-in-react-native-expo-eas-build-ebf6b8c5a8f0?source=rss-a2d16f674ddd------2</link>
            <guid isPermaLink="false">https://medium.com/p/ebf6b8c5a8f0</guid>
            <category><![CDATA[expo]]></category>
            <category><![CDATA[eas-build]]></category>
            <category><![CDATA[react-native]]></category>
            <dc:creator><![CDATA[Enzo61]]></dc:creator>
            <pubDate>Sun, 08 Sep 2024 09:24:48 GMT</pubDate>
            <atom:updated>2024-09-08T09:24:48.218Z</atom:updated>
            <content:encoded><![CDATA[<h3>Using .env value in React Native Expo EAS build</h3><h3><strong>Issue</strong></h3><p>Usually we put environmental variable in .env file, and gitignore the .env, but in EAS build, when we gitignore the .env, it will get ignored when upload to the build tools too.</p><p>Expo doc say that we can put the environmental variable in eas.json, but start from this point, solutions from offical doc, stackoverflow, blog, and LLM become confused.</p><p>There is different solutions talking about:</p><ul><li>using react-native-dotenv</li><li>importing env var by syntax like import { API_URL } from ‘<a href="http://twitter.com/env">@env</a>’;</li><li>using eas-secret</li><li>turning app.json to app.config.js</li><li>…</li></ul><h3>Solution</h3><p>This is a method that is simple, and it will duplicated the same env vars in 2 files, and not include any dynamically env var switching feature, but it works:</p><h4>Step 1</h4><p>include env value for eas build (lets use the word “production” here) in eas.json, keep the same key name as in .env, you could choose either use the same value or using different value. EAS will only get the value from eas.json</p><pre>{<br>  &quot;cli&quot;: {<br>    &quot;version&quot;: &quot;&gt;= 7.3.0&quot;<br>  },<br>  &quot;build&quot;: {<br>    &quot;development&quot;: {<br>      &quot;developmentClient&quot;: true,<br>      &quot;distribution&quot;: &quot;internal&quot;<br>    },<br>    &quot;preview&quot;: {<br>      &quot;distribution&quot;: &quot;internal&quot;,<br>      &quot;android&quot;: {<br>        &quot;buildType&quot;: &quot;apk&quot;<br>      }<br>    },<br>    &quot;production&quot;: {<br>      &quot;env&quot;: {<br>        &quot;EXPO_PUBLIC_TESTNAME&quot;: &quot;ENV_EAS&quot;,<br>        &quot;EXPO_PUBLIC_APP_ID&quot;: &quot;&lt;APP_ID&gt;&quot;,<br>        &quot;EXPO_PUBLIC_TOKEN&quot;: &quot;&lt;TOKEN&gt;&quot;<br>      },<br>      &quot;android&quot;: {<br>        &quot;buildType&quot;: &quot;apk&quot;<br>      }<br>    }<br>  },<br>  &quot;submit&quot;: {<br>    &quot;production&quot;: {}<br>  }<br>}</pre><p>As a comaprsion, in .env, we have a different TESTNAME value</p><pre>EXPO_PUBLIC_TOKEN=&lt;TOKEN&gt;<br>EXPO_PUBLIC_TESTNAME=ENV_ENV</pre><pre>return (<br>  &lt;Text&gt;{`ENV test: ${process.env.EXPO_PUBLIC_TESTNAME || &quot;empty&quot;}`}&lt;/Text&gt;<br>)</pre><h4>Step 2</h4><p>in `.gitignore`, we ignore both files, so that nothing get pushed to git</p><pre>.env<br>eas.json</pre><p>While sending files to EAS build, eas.json will not be ignored, (Althrough AI usually say it will).</p><h4>Step 3</h4><p>Perform EAS build</p><h3>Result</h3><p>ENV test: ENV_EAS displayed on app interface, env vars in eas.json were implemented to the app build</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*im0YldxLnqqFqQDNePDcpQ.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ebf6b8c5a8f0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[When updating eas-cli failed and still show the same old version]]></title>
            <link>https://medium.com/@Enzo61/when-updating-eas-cli-fail-and-still-show-the-same-old-version-d4cff7c17d37?source=rss-a2d16f674ddd------2</link>
            <guid isPermaLink="false">https://medium.com/p/d4cff7c17d37</guid>
            <category><![CDATA[expo]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[eas-build]]></category>
            <dc:creator><![CDATA[Enzo61]]></dc:creator>
            <pubDate>Sun, 08 Sep 2024 09:07:27 GMT</pubDate>
            <atom:updated>2024-09-08T09:08:51.350Z</atom:updated>
            <content:encoded><![CDATA[<h3>Issue:</h3><p>Can’t use EAS build because the eas cli is in old ver.</p><p>Tried `npm install -g eas-cli` but after successfully install, when checking version with `eas — version`, the log still show it is in old ver</p><h3>Mistake:</h3><p>I ran the command in VSCode terminal which point to project dir level.</p><h3>Solution:</h3><p>I should run the install command at the default dir level in mac terminal, with `sudo`</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d4cff7c17d37" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to run EAS build on local machine]]></title>
            <link>https://medium.com/@Enzo61/how-to-run-eas-build-on-local-machine-31335f144efc?source=rss-a2d16f674ddd------2</link>
            <guid isPermaLink="false">https://medium.com/p/31335f144efc</guid>
            <category><![CDATA[expo]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[eas-build]]></category>
            <dc:creator><![CDATA[Enzo61]]></dc:creator>
            <pubDate>Sun, 08 Sep 2024 09:04:09 GMT</pubDate>
            <atom:updated>2024-09-08T09:04:09.017Z</atom:updated>
            <content:encoded><![CDATA[<p>We can build app through EAS from local without waiting to upload and queue.</p><p>The commmand to run on local is</p><pre>eas build --local</pre><p>This method only work for Mac and Linux for building apps for Android. — 2024 Sep</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=31335f144efc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Problem faced to setup auth through Expo Router in React Native (index can’t find, infinite loop)]]></title>
            <link>https://medium.com/@Enzo61/problem-faced-to-setup-auth-through-expo-router-in-react-native-index-cant-find-infinite-loop-a168bab0577e?source=rss-a2d16f674ddd------2</link>
            <guid isPermaLink="false">https://medium.com/p/a168bab0577e</guid>
            <category><![CDATA[expo-router]]></category>
            <category><![CDATA[react-native]]></category>
            <dc:creator><![CDATA[Enzo61]]></dc:creator>
            <pubDate>Fri, 30 Aug 2024 01:57:20 GMT</pubDate>
            <atom:updated>2025-02-04T23:27:15.735Z</atom:updated>
            <content:encoded><![CDATA[<h4>Background</h4><p>I was new to expo-router and wanted to use it in a green field project. At the beginning I used a structure that contains Tabs, I followed the file structure that Expo provided, and things go smooth.</p><p><a href="https://docs.expo.dev/router/advanced/tabs/">https://docs.expo.dev/router/advanced/tabs/</a></p><pre>/app<br>  /_layout.tsx<br>  /(tabs)/<br>    /_layout.tsx<br>    /index.tsx<br>    /setting.tsx<br></pre><p>In the above structure, the entry point of the app will be app/(tabs)/index.tsx</p><p>And then, I wanted to include auth in my app.<br>Expo porvided tutorial on how to set up auth with Expo Router. However, it didn’t mention how to do it with Tabs, so i tried myself.</p><p><a href="https://docs.expo.dev/router/reference/authentication/">https://docs.expo.dev/router/reference/authentication/</a></p><h4>The first try</h4><p>This is how I arranged my routing logic at the beginning:</p><p><strong>Dir structure</strong></p><pre>--/app<br>  --/(tabs)/<br>  --/auth/<br>    --/otp/<br>      --/otpAuth.tsx<br>    --/loginAuth.tsx<br>  --/layout.tsx<br>  --/+html.tsx<br>  --/+not-found.tsx</pre><p><strong>at rootlayout</strong></p><pre><br>  return (<br>    &lt;&gt;<br>      { isLoggedIn ? (<br>        &lt;&gt;<br>          &lt;Stack&gt;<br>            &lt;Stack.Screen name=&quot;(tabs)&quot; options={{ headerShown: false }} /&gt;<br>            &lt;Stack.Screen name=&quot;+not-found&quot; /&gt;<br>          &lt;/Stack&gt;<br>        &lt;/&gt;<br>      ) : (<br>        &lt;&gt;<br>          &lt;Stack&gt;<br>            &lt;Stack.Screen <br>              name=&quot;auth&quot; <br>              options={{ headerShown: false }}<br>            /&gt;<br>          &lt;/Stack&gt;<br>        &lt;/&gt;<br>      )}<br>    &lt;/&gt;<br>  )</pre><h4>Why it doesn’t work</h4><p>There are a few misunderstanding of the concept of file based routing:</p><p>1. The `&lt;Stack/&gt;` is just some styling things that manage how the top nav bar looks like, it doesn’t contains any routing logic, although it looks like it is managing routing.</p><p>2. Expo Router always look for `index.tsx` as the entry of the app, in this dir structure, the order of the files that will be ran are:</p><ul><li>/app/_layout</li><li>/app/(tabs)/_layout</li><li>/app/(tabs)/index</li></ul><p>Thanks to the help from the support from Expo Discord channel, instructor from Expo suggested me to prevent the rendering of the rest of the app until I have checked the user has authenticated, and if they are not, Redirect them to auth route</p><h4>The second try</h4><pre> --/app/<br>  --/auth/<br>    --/_layout.tsx<br>    --/emailAuth.tsx<br>    --/otpAuth.tsx<br>  --/list/<br>    --/index.tsx<br>    --/_layout.tsx<br>  --/layout.tsx<br>  --/+not-found.tsx</pre><p>In the second try, I created a blank testing project to test more about the gate and redirect logic without Tabs, I included a index.tsx in /list, but it doesn’t route me to there as an entry, the app complain that it can’t find a entry.</p><p>The reason behind that is, the index.tsx is hidden under /list/</p><p>WHY ROUTER CAN FIND IT IN ???</p><pre>/app<br>  /_layout.tsx<br>  /(tabs)/<br>    /_layout.tsx<br>    /index.tsx<br>    /setting.tsx</pre><p>It is because, /(tabs)/ is like a visual representation to the developer to visually group the nested files together, it didn’t logically make it a child level. (But not 100%, becuase the layout file count… so it is a bit tricky here…)</p><p>If you imagine the above structure as a html folder called “app”, the files are actually in a structre like:</p><pre>/app<br>  /_layout.tsx<br>  /(tabs)/_layout.tsx<br>  /(tabs)/index.tsx<br>  /(tabs)/setting.tsx</pre><p>This is why Expo can find a index file as a entry in root level (even the /(tabs)/index.tsx is under /(tabs)/</p><p>The third try</p><p>The third tryout success, it landed the Index in root first, then redirect to /(protected)/list/listScreen, but when it pass through (protected), the (protected)/_layout act as a gate to redirect the app to other screen according to condition.</p><pre>/app/<br>  /(protected)/<br>    /list/<br>      /_layout.tsx<br>      /listScreen.tsx<br>    /_layout.tsx<br>  /auth/<br>    /_layout.tsx<br>    /emailAuth.tsx<br>    /otpAuth.tsx<br> /_layout.tsx<br> /index.tsx</pre><pre>// app/index<br>export default function Index() {<br><br>  return(<br>    &lt;Redirect href={&#39;/(protected)/list/listScreen&#39;}/&gt;<br>  )<br>}</pre><pre>// (protected)/_layout<br>export default function protectedLayout() {<br><br>  const isEmailAuthed = useAppSelector((state) =&gt; state.emailAuthSlice.emailAuthState);<br>  const isOtpAuthed = useAppSelector((state) =&gt; state.otpAuthSlice.otpAuthState);<br><br>  if (!isOtpAuthed) {<br>    if (!isEmailAuthed) {<br>      console.log(&quot;!isEmailAuthed, trigger redirect&quot;);<br>      return(<br>        &lt;Redirect href={&#39;/auth/emailAuth&#39;}/&gt;<br>      )<br>    }<br>    console.log(&quot;!isOtpAuthed, trigger redirect&quot;);<br>      return(<br>        &lt;Redirect href={&#39;/auth/otpAuth&#39;}/&gt;<br>      )<br>  } else {<br>    return (<br>      &lt;Slot/&gt;<br>    )<br>  }<br>}</pre><h4>Move from testing project to working project, faced infinite loop</h4><p>After I ran the routing successfully in testing project , I moved to setup the working project with tabs, but I faced a infinite loop issue while redirecting:</p><pre>/app/<br>  /(app)/<br>    /(protected)/<br>      /(tabs)/<br>        /_layout.tsx<br>        /index.tsx<br>        /setting.tsx<br>        /testingScreen.tsx<br>    /auth/<br>      /_layout.tsx<br>      /emailAuth.tsx<br>      /otpAuth.tsx<br>    /_layout.tsx &lt;-- Gate Infinite Loop<br>  /_layout.tsx</pre><p>in this dir structure, the gate for redirect the un-auth users is at (app)/_layout, it use &lt;Redirect/&gt; to redirect users from pointing to /app/(app)/(protected)/(tabs)/index become pointing to /app/(app)/auth/emailAuth/</p><p>However, it becomes an infinite loop, after the gate tried to redirect the user to index, it actually fire the root layout again.</p><p>I believe the reason behind thisis, when using &lt;Redirect/&gt;, it actually start calculating the route from root again, therefore, it pass through the gate again and caused a infinite loop.</p><p>Therefore, I decided to move the gate one level under</p><h4>Final</h4><pre>/app/<br>  /(app)/<br>    /(protected)/<br>      /(tabs)/<br>        /_layout.tsx<br>        /index.tsx<br>        /setting.tsx<br>        /testingScreen.tsx<br>      /_layout  &lt;-- gate OK<br>    /auth/<br>      /_layout.tsx<br>      /emailAuth.tsx<br>      /otpAuth.tsx<br>  /_layout.tsx</pre><p>The gate is now in /app/(app)/(protected)/_layout</p><p>The index file is in /app/(app)/(protected)/(tabs)/index where it is still in the root level.</p><p>When router try to land index, it pass through gate at /app/(app)/(protected)/_layout, at there, it route the un-auth user to emailAuth.</p><h3>Some useful link</h3><p>- Why the (tabs) grouping: <a href="https://x.com/kadikraman/status/1811333443227136476">https://x.com/kadikraman/status/1811333443227136476</a></p><p>- Must we use index files: <a href="https://x.com/kadikraman/status/1816583383423881650">https://x.com/kadikraman/status/1816583383423881650</a></p><p>- How to handle authenticated routes: <a href="https://x.com/kadikraman/status/1827347187581206665">https://x.com/kadikraman/status/1827347187581206665</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a168bab0577e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learning Note — How to switch between Development and Production environment with dotenv, in…]]></title>
            <link>https://medium.com/@Enzo61/learning-note-how-to-switch-between-development-and-production-environment-with-dotenv-in-4db4c9e8cce2?source=rss-a2d16f674ddd------2</link>
            <guid isPermaLink="false">https://medium.com/p/4db4c9e8cce2</guid>
            <dc:creator><![CDATA[Enzo61]]></dc:creator>
            <pubDate>Wed, 24 Jul 2024 22:28:28 GMT</pubDate>
            <atom:updated>2024-07-25T00:33:54.198Z</atom:updated>
            <content:encoded><![CDATA[<h3>Learning Note — How to switch between Development and Production environment with dotenv, in Express JS</h3><p>This article talks about how to setup a minimal ExpressJS App to load different environment variables to the App depends on launching the app in Dev / Production (or UAT.. pre-prod.. as u like) environment.</p><h4>0. Deliverable, and whole project strucutre</h4><p>Deliverable:</p><ul><li>When the server runs in Dev environment, in console log, there will be Yo, This is DEV environment , which the string DEV is loaded from environment variables.</li><li>When the server runs in Production environment, in console log, there will be Yo, This is PRODUCTION environment , which the string PRODUCTION is loaded from environment variables.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/448/1*4jqRANDHm-M7gZfGv4_0hQ.png" /></figure><ul><li>whole project structure:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/565/1*ExF6lkuhYADSy1EIfLB6iA.png" /></figure><h4>1. Setup your Express App</h4><pre>cd ~/Projects<br>mkdir my-express-app<br>cd my-express-app<br>npm init -y<br>npm install express<br>touch src/index.ts</pre><h4>2. Install TypeScript and ts-node</h4><p>ts-node is a TypeScript execution engine and REPL for Node.js.</p><p>It transforms TypeScript into JavaScript, enabling you to directly execute TypeScript on Node.js without precompiling. It usually be used in only dev environment.</p><ul><li>install usingnpm install typescript ts-node — save-dev</li></ul><p>Add a tsconfig.json file to the root directory npx tsc --init to setup TypeScript config</p><pre>{<br>  &quot;compilerOptions&quot;: {<br>    &quot;target&quot;: &quot;ES6&quot;,                         // Use ES6 for more modern JavaScript features.<br>    &quot;module&quot;: &quot;commonjs&quot;,                    // CommonJS for Node.js compatibility.<br>    &quot;outDir&quot;: &quot;./dist&quot;,                      // Directory for compiled JavaScript files.<br>    &quot;rootDir&quot;: &quot;./src&quot;,                      // Root directory of TypeScript source files.<br>    &quot;esModuleInterop&quot;: true,                 // Enable compatibility with CommonJS modules.<br>    &quot;forceConsistentCasingInFileNames&quot;: true, // Ensure consistent casing in filenames.<br>    &quot;strict&quot;: true,                          // Enable all strict type-checking options.<br>    &quot;skipLibCheck&quot;: true                     // Skip type checking of declaration files for faster compilation.<br>  },<br>  &quot;include&quot;: [&quot;src/**/*&quot;],                  // Include all files in the src directory.<br>  &quot;exclude&quot;: [&quot;node_modules&quot;]               // Exclude node_modules from compilation.<br>}</pre><h4>3. Install dotenv</h4><p>Dotenv is a zero-dependency module that loads environment variables from a .env file into process.env. Storing configuration in the environment separate from code</p><pre>npm install dotenv</pre><h4>4. Create two file under root directory</h4><p>to contains environment variables with different value</p><p><strong>.env</strong></p><pre>EXPRESS_PORT=3000<br>WELCOME=&quot;This is DEV environment&quot;</pre><p><strong>.env.production</strong></p><pre>EXPRESS_PORT=3000<br>WELCOME=&quot;This is PRODUCTION environment&quot;</pre><h4>5. config package.json</h4><pre>&quot;scripts&quot;: {<br>  &quot;build&quot;: &quot;tsc&quot;,<br>  &quot;dev&quot;: &quot;NODE_ENV=development ts-node src/index.ts&quot;,<br>  &quot;prod&quot;: &quot;npm run build &amp;&amp; NODE_ENV=production node dist/index.js&quot;<br>},</pre><p><strong>**build:**</strong> This script runs TypeScript compiler (tsc) to transpile TypeScript files to JavaScript.</p><p><strong>**dev:**</strong> This <strong>sets NODE_ENV to ‘development’</strong> and runs the TypeScript file directly using ts-node.</p><p><strong>**prod:**</strong> This first builds the project (npm run build), then <strong>sets NODE_ENV to ‘production’</strong> and runs the compiled JavaScript file.</p><h4>6. config src/index.ts</h4><pre>import express, { Request, Response } from &quot;express&quot;;<br>import dotenv from &#39;dotenv&#39;;<br>import path from &#39;path&#39;;<br><br>const env = process.env.NODE_ENV || &#39;development&#39;;<br>const envPath = path.resolve(process.cwd(), `.env${env === &#39;development&#39; ? &#39;&#39; : &#39;.&#39; + env}`);<br><br>console.log(`Loading .env file: ${envPath}`);<br>dotenv.config({ path: envPath });<br><br>const app = express();<br>const port = process.env.EXPRESS_PORT || 3000;<br><br>app.use(express.json());<br><br>app.get(&quot;/&quot;, (req: Request, res: Response) =&gt; {<br>  res.send(&#39;Welcome to the server&#39;);<br>});<br><br>app.listen(port, () =&gt; {<br>  console.log(`Server running on port ${port}`);<br>})<br><br>console.log(`Yo, ${process.env.WELCOME}`);<br>console.log(&#39;NODE_ENV:&#39;, process.env.NODE_ENV);</pre><ul><li>The code first determines the environment: const env = process.env.NODE_ENV || ‘development’; sets env to the value of NODE_ENV if it’s set, or ‘development’ if it’s not.</li><li>It then constructs the path to the appropriate .env file: const envPath = path.resolve(process.cwd(), `.env${env === ‘development’ ? ‘’ : ‘.’ + env}`); This creates a path to .env for development, or .env.production for production.</li></ul><p><strong>**path library:**</strong> The path module is a built-in Node.js module that provides utilities for working with file and directory paths. It helps in handling and transforming file paths across different operating systems.</p><p><strong>**path.resolve():**</strong> a method in the path module that resolves a sequence of paths or path segments into an absolute path. It processes the arguments from right to left, prepending each subsequent path until an absolute path is constructed.</p><p><strong>**process.cwd():**</strong> a method in Node.js that returns the current working directory of the Node.js process. CWD stands for “Current Working Directory”. (the `npm run dev` is from package.json that located at root directory so process.cwd() is pointing to root directory.</p><p><strong>**When Run:**</strong> in `path.resolve()`, `process.cwd()` first get the current dir, then in the template literal, check if `env === development`, if not, path is `.env`, if not, path is `.env${env}` (note that the second env is a var in index.ts script)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4db4c9e8cce2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Principles inspired by LiXiaoLai]]></title>
            <link>https://medium.com/@Enzo61/principles-inspired-by-lixiaolai-d8e180044ab0?source=rss-a2d16f674ddd------2</link>
            <guid isPermaLink="false">https://medium.com/p/d8e180044ab0</guid>
            <dc:creator><![CDATA[Enzo61]]></dc:creator>
            <pubDate>Wed, 10 Jul 2024 22:57:21 GMT</pubDate>
            <atom:updated>2024-07-10T23:03:32.064Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hxjBbg6N-dKtnGx7sCpE5g.jpeg" /></figure><p>LiXiaoLai is often described as “China’s richest Bitcoin billionaire”, people believe that he helds 100,000 Bitcoins and has successfully cashed out 13.5 billion RMB.</p><p>He started his adventure by first being a computer sales, then an English teacher at the famous english school “New Oriental”- NYSE: EDU and published his own book. Then, he start to buy bitcoin from $1 and hold. He is also described as a “cheater” or “scammer” because of a leaked recording about his comment on cryptocurrency and crypto exchange.</p><p>I read some of his books, such as “Time as a Friend” and “Reborn”. Those are great books and are free if you read from his GitHub, but there are only Chinese version on his GitHub.</p><p>I selected these principles when I tried to extract 8 top principles from Li’s thought (because I am using the mandala thinking method),.</p><h3>Principle 1</h3><h4>Be confident in your future. One’s skill and wisdom can be improved through learning and practice.</h4><p>It doesn’t matter if you are not confident with your present or past. Confidence can be like the stock market, which always going up and down, that is normal and doesn’t matter. Be self-abased when you need to. Pretend to be confident when you don’t have. Try not to compare to other people. When you want to compare, compare your past to your present and future.</p><h3>Principle 2</h3><h4>Believe that you will have good luck</h4><p>To increase your odds: <br>- Be open-minded. <br>- Keep a proper amount of randomness in your life. <br>- Create more connections<br>- Putting effort into multiple things at the same time</p><h3>Principle 3</h3><h4>Be Proactive. Do the correct things even through they are not what you are good at or familiar with.</h4><p>Accumulate and believe that you will catch at least one good oppurtunity to perform because of your ability.</p><h3>Principle 4</h3><h4>When you try to learn something and can’t understand, keep study, learn for many times.</h4><p>Success is unlike climbing a mountain because the path to success is usually unclear. It is more like using a shove to break a thick ice surface on a forzen lake. You dig on the left and dig on the right, trying to find the weakest part of the ice, nothing seems to be working, but when you keep digging in all possible directions, suddenly, the ice breaks, and you fall into the water successfully.</p><h3>Principle 5</h3><h4>Not accepting any “fragmented XX”</h4><p>No “fragmented study”, no “fragmented entertainment”… I don’t want a fragmented life.</p><p><a href="https://www.crunchbase.com/person/xiaolai-li">https://www.crunchbase.com/person/xiaolai-li</a></p><p><a href="https://www.amazon.com/Books-Li-Xiaolai/s?rh=n%3A283155%2Cp_27%3ALi+Xiaolai">https://www.amazon.com/Books-Li-Xiaolai/s?rh=n%3A283155%2Cp_27%3ALi+Xiaolai</a></p><p><a href="https://github.com/xiaolai">xiaolai (xiaolai) (github.com)</a></p><p><a href="https://en.wikipedia.org/wiki/Li_Xiaolai">Li Xiaolai — Wikipedia</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d8e180044ab0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Principles inspired by Shane Parrish]]></title>
            <link>https://medium.com/@Enzo61/principles-inspired-by-shane-parrish-bdbba5d7e013?source=rss-a2d16f674ddd------2</link>
            <guid isPermaLink="false">https://medium.com/p/bdbba5d7e013</guid>
            <dc:creator><![CDATA[Enzo61]]></dc:creator>
            <pubDate>Tue, 09 Jul 2024 23:19:02 GMT</pubDate>
            <atom:updated>2024-07-10T23:01:49.851Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*5yaocaxlmxqGQmbovDTdrg.png" /></figure><p>I know the name Shane Parrish from the podcast and post by Tim Ferriss and Naval Ravikant.</p><p>Shane Parrish was employed by US intelligence agency. He found that the wisdom from the titans of industries helped him make better decisions. To catalog his learning, he founded the website Farnam Street, which aims to extract evergreen wisdom about mental model and decision-making from different “titans” such as Charlie Munger and Daniel Kahneman.</p><p>I bought his book “Thinking Clear — Turning Ordinary Moments into Extraordinary Results”. The book is about decision making, the part 1 of the book is bored but it turns great from part 2. The book provided a ton of useful knowledge, but when I have to extract 8 top principles from it (because I am using the mandala thinking method), I found this top 3.</p><h3>Principle 1</h3><h4>The decisions you make in ordinary moments forge your life</h4><p>We know the importance of the big decisions, like finding a good job and a good wife. However, we sometimes forget the importance of ordinary moments and the minor decisions from that moment. For example, how we handle our emotions to a colleague in a meeting. Each minor decision puts us in a better or worse position to handle the future.</p><h3><strong>Principle 2</strong></h3><h4>Put yourself in a good position</h4><p>Hard work is needed but not enough. We have to put ourselves in a good position. You may look genius when you are in a good position, even though you may not be that good. You can look stupid when you are in a wrong and bad position even though you are smart.</p><p>Miyamoto Musashi is good at fighting skills, and he even uses sunlight direction and time to put himself in a good position when fighting.</p><h3>Principle 3</h3><h4>Will this decision make the future easier or harder</h4><p>When we want to do something that we know is not good but we still want to do it, this can be one of the blockers we can add when we are trying to make the decision.</p><p><a href="https://fs.blog/">Learn faster, Think better, and make Smart Decisions (fs.blog)</a></p><p><a href="https://www.amazon.com.au/Clear-Thinking-Turning-Ordinary-Extraordinary/dp/1529915953/ref=asc_df_1529915953/?tag=googleshopdsk-22&amp;linkCode=df0&amp;hvadid=649997435719&amp;hvpos=&amp;hvnetw=g&amp;hvrand=5146827376321815871&amp;hvpone=&amp;hvptwo=&amp;hvqmt=&amp;hvdev=c&amp;hvdvcmdl=&amp;hvlocint=&amp;hvlocphy=9071335&amp;hvtargid=pla-2253317159247&amp;psc=1&amp;mcid=8911d1b2931e3a518b8cecc23abd98be">Clear Thinking: Turning Ordinary Moments into Extraordinary Results : Parrish, Shane: Amazon.com.au: Books</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bdbba5d7e013" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>