<?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 Clare Mburu on Medium]]></title>
        <description><![CDATA[Stories by Clare Mburu on Medium]]></description>
        <link>https://medium.com/@claremburu?source=rss-14ed3a31edab------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*sJs5dUys0Ip00SeRqYx84Q.jpeg</url>
            <title>Stories by Clare Mburu on Medium</title>
            <link>https://medium.com/@claremburu?source=rss-14ed3a31edab------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 14:22:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@claremburu/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[Building your own mobile Fintech with Crossmint]]></title>
            <link>https://claremburu.medium.com/building-your-own-mobile-fintech-with-crossmint-c3b3e35b0771?source=rss-14ed3a31edab------2</link>
            <guid isPermaLink="false">https://medium.com/p/c3b3e35b0771</guid>
            <category><![CDATA[expo]]></category>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[stable-coin]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[crossmint]]></category>
            <dc:creator><![CDATA[Clare Mburu]]></dc:creator>
            <pubDate>Wed, 11 Feb 2026 19:18:10 GMT</pubDate>
            <atom:updated>2026-02-11T19:18:10.889Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nhZeE5ok-VmFFW_ka93LCA.png" /></figure><p>Nothing beats seeing your idea come to life.</p><p>Let’s be honest: most fintech ideas never make it past the ‘good idea’ stage because the infrastructure is a nightmare.</p><p>I’m writing this because it doesn’t have to be that way. We’re going to use React Native(Expo) and Crossmint to skip the headache and focus on what matters. By the time we’re done, you’ll have a production-grade app, not just another ‘work-in-progress’ folder on your desktop.</p><h4>TL;DR</h4><p>The code for this tutorial is open sourced and you can find a fully working implementation on <a href="https://github.com/devclarenjoki/mobile-fintech-crossmint">Github</a>.</p><h4>Why Crossmint?</h4><p>Crossmint is like Stripe for Web3. Why do I say this? Because it abstracts the complexities of generating a 12-word seed phrase for your wallet, has lower transaction fees(this is good for business), their transactions happen at the speed of light(they happen instantly), and the cherry on top of the cake — they let you choose your smart contract of choice(e.g, Base, Solana, Stellar, just to name a few). In simple terms, Crossmint handles the messy backend of the blockchain, so you don’t have to. I heard they have a name for this: Seedless wallets</p><h4>Who is this for?</h4><p>This tutorial is beginner friendly, as you do not need to be conversant with blockchain to get started. However, the tutorial assumes you have knowledge in React Native and Typescript.</p><h3>Prerequisites</h3><p>We’ll need the following to get started:<br>1. Node.js (LTS version) installed in your computer<br>2. Expo Go installed on a physical device(you will get this on Playstore or App Store)<br>3. VS Code or any other preferred code editor or IDE installed<br>4. A macOS, Linux, or Windows (PowerShell and WSL2) with a terminal window open.</p><h3>Getting Started</h3><p>We will use bun as my package manager of choice. Feel free to use npm, pnpm, yarn or any package manager of your choice. If you are interested in setting up bun on your computer, follow this <a href="https://bun.com/docs/quickstart">guide</a>.</p><p>On your terminal of choice, run this</p><pre>bun create expo-app xMint-mobile</pre><p>After all the packages are installed:</p><pre>cd xMint-mobile</pre><p>Let’s import crossmint in our project:</p><pre>bun expo install @crossmint/client-sdk-react-native-ui</pre><p>If you haven’t already, create a Crossmint developer account <a href="https://staging.crossmint.com/console">here</a>. After you’re done head over to the <a href="https://staging.crossmint.com/console/overview">staging console</a>. Here you will find your server and client API keys. Create a .<em>env </em>in your root folder and save the credentials because we will be using them throughout the project.</p><blockquote>As part of Expo’s naming convention, the Expo CLI will automatically load environment variables with an EXPO_PUBLIC_ prefix from .env files for use within your JavaScript code</blockquote><p>That said, your .<em>env</em> should look like this</p><pre>EXPO_PUBLIC_API_CLIENT_KEY = &quot;YOUR CLIENT API KEY&quot;<br><br>EXPO_PUBLIC_API_SERVER_KEY = &quot;YOUR SERVER API KEY&quot;</pre><p>In your now launched project, we will start by configuring CrossmintProviders in your root layout. We will use base-sepolia as our chain of choice then for the signer we will use email.</p><p><a href="https://github.com/devclarenjoki/mobile-fintech-crossmint/blob/refactor/app/providers/CrossmintProviders.tsx">mobile-fintech-crossmint/app/providers/CrossmintProviders.tsx at refactor · devclarenjoki/mobile-fintech-crossmint</a></p><p>First things first, let’s authenticate the user.<br>1. Login flow:</p><p>We will implement login with google and email. Since the <em>status </em>from Crossmint tells us exactly whether the user is logged in or out, we can use that to return different navigation stacks. The login process follows a two-step verification flow.</p><p><a href="https://github.com/devclarenjoki/mobile-fintech-crossmint/blob/refactor/components/ui/login.tsx">mobile-fintech-crossmint/components/ui/login.tsx at refactor · devclarenjoki/mobile-fintech-crossmint</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*3C_Fg1jPJkS6z4mFALy12Q.jpeg" /></figure><p>On successful login or once the data is ready, the user sees their account with their details.</p><p><a href="https://github.com/devclarenjoki/mobile-fintech-crossmint/blob/refactor/components/Dasboard/dashboard.tsx">mobile-fintech-crossmint/components/Dasboard/dashboard.tsx at refactor · devclarenjoki/mobile-fintech-crossmint</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*MzCQbocFDrxdGJ34h2IcPQ.jpeg" /></figure><p>To add staging tokens to your account, use <a href="https://faucet.circle.com/">https://faucet.circle.com/</a></p><p>Now that the dashboard is ready, lets basic perform wallet functions:</p><ol><li>Send</li><li>Request</li><li>Buy Crypto</li><li>Transaction History</li></ol><p>Send</p><p>This component handles the user input for a recipient address and amount. For the first time, user is required to verify their email</p><p><a href="https://github.com/devclarenjoki/mobile-fintech-crossmint/blob/refactor/app/send.tsx">mobile-fintech-crossmint/app/send.tsx at refactor · devclarenjoki/mobile-fintech-crossmint</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*PTkjozbZ0trGqELozzb2IA.jpeg" /></figure><p>Request:<br>For receiving, the most important thing is showing the wallet address and ideally a QR code that has the user’s wallet information</p><p><a href="https://github.com/devclarenjoki/mobile-fintech-crossmint/blob/refactor/app/receive.tsx">mobile-fintech-crossmint/app/receive.tsx at refactor · devclarenjoki/mobile-fintech-crossmint</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*ffczs6aZ-YhUABKzeHxupQ.jpeg" /></figure><p>Buy</p><p>For <strong>Buy</strong>, Crossmint usually provides a CrossmintPayButton or a hosted checkout URL.</p><p><a href="https://github.com/devclarenjoki/mobile-fintech-crossmint/blob/refactor/components/Dasboard/buycrypto.tsx">mobile-fintech-crossmint/components/Dasboard/buycrypto.tsx at refactor · devclarenjoki/mobile-fintech-crossmint</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*aQxDVQzEr0PkjSW0ySZEcA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*HNpHN3yoxaYfn3bwf8Yvbg.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*Z35hP2e5ZI7H7_vwn8qG9A.jpeg" /></figure><p>Transaction History</p><p>For <strong>History</strong>, we fetch the transaction list from the wallet.</p><p><a href="https://github.com/devclarenjoki/mobile-fintech-crossmint/blob/refactor/components/Dasboard/history.tsx">https://github.com/devclarenjoki/mobile-fintech-crossmint/blob/refactor/components/Dasboard/history.tsx</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*CLPRQ8x-xQfwFIG7Rjr8cQ.jpeg" /></figure><p>And there you have it. A fully-fledged mobile fintech that allows you to send, recieve, buy crypto and see transactions in realtime. It’s recommended to test end-to-end on staging before moving to production</p><h4>On going to Production</h4><p>There are a few changes to make before going to production and I actually have a basic checklist for this:</p><ol><li>Whitelist domains on your crossmint console. In our case add your package name inside app.json. e.g. com.example.app</li><li>Change server and client api keys in the <em>.env</em> to production credentials</li><li>Change url from <a href="https://staging.crossmint.com/">https://staging.crossmint.com</a> to <a href="https://staging.crossmint.com/">https://crossmint.com</a></li><li>Change any testnet chains to mainnet. In our case, we have been using base-sepolia, so we will change it to base.</li></ol><h3>Troubleshooting Common `useWallet` Issues</h3><p>While the Crossmint SDK is powerful, I encountered specific edge cases when integrating it into React Native application. Based on our implementation, here is the most critical “known issue” and how to resolve it.</p><h4>1. The “Null Value” Crash on Initialization</h4><p>You might see your app crash immediately with the following error as soon as it boots:</p><blockquote>ERROR [Error: Uncaught (in promise, id: 67) TypeError: Cannot convert null value to object]</blockquote><p>You might notice your network tab flooding with repeated balance requests, or errors like `Stack overflow` or `Uncaught promise` repeating dozens of times (e.g., “67 errors”). This usually happens right after login or during rapid re-renders.</p><p><strong>The Cause:<br></strong>This is a classic <em>Race Condition</em>.<br>1. `useWallet` updates its state.<br>2. This triggers a `useEffect` in your component to fetch the balance.<br>3. The fetch updates your component’s state.<br>4. The state update causes a re-render.<br>5. `useEffect` fires <em>again</em> before the previous fetch has finished.</p><p>Without a guard clause, these requests stack on top of each other, creating a “polling storm” that hits your API limits and creates an unstable UI.</p><p><strong>The Robust Solution: The Wrapper Component</strong></p><p>To solve both issues simultaneously, the cleanest architectural pattern is to encapsulate the `useWallet` logic into a custom hook or wrapper component. This isolates the null checks and race conditions away from your UI code, ensuring your Dashboard only renders when the wallet is truly ready and stable.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c3b3e35b0771" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Integrating Crossmint into Your Expo App: A Developer’s Journey]]></title>
            <link>https://claremburu.medium.com/integrating-crossmint-into-your-expo-app-a-developers-journey-68b8e51341d5?source=rss-14ed3a31edab------2</link>
            <guid isPermaLink="false">https://medium.com/p/68b8e51341d5</guid>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[benkiko-finance]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[crossmint]]></category>
            <dc:creator><![CDATA[Clare Mburu]]></dc:creator>
            <pubDate>Fri, 21 Nov 2025 16:14:54 GMT</pubDate>
            <atom:updated>2025-12-07T19:02:35.112Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-fg962rsMtitd83I9EaZWQ.png" /></figure><p>I recently tried developing a web3 application and found myself hitting unexpected roadblocks.In this guide, I’ll walk you through my experience, sharing the solutions I discovered along the way. By the end, you’ll have a working Crossmint integration in your Expo app, complete with wallet creation, funding, and token transfers.</p><h4>Setting the Stage: Project Setup</h4><p>Before diving into the fun stuff, let’s get our project ready. I’ll be using Bun as my package manager, but feel free to use npm, yarn, or pnpm if that’s more your style.</p><pre>bun create expo-app wallet-crossmint</pre><p>Next, you’ll need to create a Crossmint account and set up a new project in the Staging Console. Here’s how:</p><ol><li>Head over to [Crossmint’s staging console](<a href="https://staging.crossmint.com/">https://staging.crossmint.com</a>) and create an account<br>2. Create your first project (you’ll be taken directly there if you’re a new user)<br>3. Grab your API keys from the project overview and store them securely in your .envfile</li></ol><blockquote><em>🌟 Pro-Tip: For Expo to read your environment variables, you must prefix them with </em><em>EXPO_PUBLIC_.</em></blockquote><p>Your .env file should look like this:</p><pre>EXPO_PUBLIC_CROSSMINT_API_KEY=&quot;your_client_api_key_here&quot;</pre><p>Now, let’s install the Crossmint SDK:</p><pre>bun expo install @crossmint/client-sdk-react-native-ui</pre><h4>Building the Foundation: Crossmint Providers</h4><p>With our project set up, it’s time to lay the foundation by configuring the Crossmint providers. This is where we’ll define how users can interact with our wallet system.</p><p>First, let’s create a provider component that wraps our application:</p><pre>import React from &quot;react&quot;;<br>import {<br>    CrossmintAuthProvider,<br>    CrossmintProvider,<br>    CrossmintWalletProvider,<br>} from &quot;@crossmint/client-sdk-react-native-ui&quot;;<br><br>interface CrossmintProvidersProps {<br>  children: React.ReactNode;<br>}<br><br>export default function CrossmintProviders({ children }: CrossmintProvidersProps) {<br>  return (<br>    &lt;CrossmintProvider apiKey={process.env.CROSSMINT_API_KEY}&gt;<br>      &lt;CrossmintAuthProvider&gt;<br>        &lt;CrossmintWalletProvider<br>          createOnLogin={{<br>            chain: &quot;base-sepolia&quot;, // or your preferred chain<br>            signer: {<br>              type: &quot;email&quot;, // We&#39;ll discuss this more below<br>            },<br>          }}<br>        &gt;<br>          {children}<br>        &lt;/CrossmintWalletProvider&gt;<br>      &lt;/CrossmintAuthProvider&gt;<br>    &lt;/CrossmintProvider&gt;<br>  );<br>}</pre><p>Now, let’s create an authentication context that will help us manage different sign-in methods:</p><pre>import React, { createContext, useContext, useState } from &#39;react&#39;;<br>const AuthContext = createContext();<br>export const useAuth = () =&gt; {<br> const context = useContext(AuthContext);<br> if (!context) {<br> throw new Error(&#39;useAuth must be used within an AuthProvider&#39;);<br> }<br> return context;<br>};<br>export const AuthProvider = ({ children }) =&gt; {<br> const [authMethod, setAuthMethod] = useState(&#39;email&#39;);<br>const getSignerConfig = () =&gt; {<br> switch (authMethod) {<br> case &#39;email&#39;:<br> return { type: &#39;email&#39; };<br> case &#39;passkey&#39;:<br> return { type: &#39;passkey&#39; };<br> case &#39;google&#39;:<br> return { type: &#39;google&#39; };<br> default:<br> return { type: &#39;email&#39; };<br> }<br> };<br>return (<br> &lt;AuthContext.Provider value={{ authMethod, setAuthMethod, getSignerConfig }}&gt;<br> {children}<br> &lt;/AuthContext.Provider&gt;<br> );<br>};</pre><p>Finally, let’s update our app’s root layout to include these providers:</p><p>app/_layout.tsx</p><pre>import AuthProvider from &#39;@/app/(auth)/AuthContext&#39;;<br>import CrossmintProviders from &#39;@/components/auth/CrossmintProviders&#39;;<br>export default function RootLayout() {<br>    return (<br>        &lt;ThemeProvider value={colorScheme === &#39;dark&#39; ? DarkTheme : DefaultTheme}&gt;<br>            &lt;AuthProvider&gt;<br>                &lt;CrossmintProviders&gt;<br>                    {/* Your app&#39;s navigation and screens */}<br>                    &lt;Stack initialRouteName=&quot;onboarding&quot; screenOptions={{ headerShown: false }}&gt;<br>                        &lt;Stack.Screen name=&quot;onboarding&quot; /&gt;<br>                    &lt;/Stack&gt;<br>                &lt;/CrossmintProviders&gt;<br>            &lt;/AuthProvider&gt;<br>        &lt;/ThemeProvider&gt;<br>    );<br>}</pre><h4>Creating Wallets: Authentication Made Simple</h4><p>With our foundation in place, users can now create wallets using different authentication methods. In our example, we’ve set up email and Google authentication, but you could easily extend this to include passkeys or an external wallet.</p><p>When a user signs in with their email, Crossmint automatically creates a wallet for them associated with that email address. This seamless experience is one of the things I love about Crossmint!</p><h4>Funding Wallets: Getting Test Tokens</h4><p>Before we can transfer tokens, we need some in our wallet. For testing purposes, you can use [faucet.circle](<a href="https://faucet.circle.com/">https://faucet.circle.com</a>) to get test tokens for the testnet.</p><h4>The Challenge: Transferring Tokens with OTP Verification</h4><p>Here’s where things got interesting for me. When implementing token transfers with email-authenticated wallets, I discovered that Crossmint requires an additional verification step: One-Time Password (OTP) verification.</p><p>This makes sense from a security perspective, but it wasn’t immediately clear in the documentation. Let me walk you through how to handle this properly.</p><h4>Basic Transfer Implementation</h4><p>First, let’s look at how to initiate a transfer:</p><pre>import { useWallet, useWalletEmailSigner } from &#39;@crossmint/client-sdk-react-native-ui&#39;;<br>export default function TokenTransfer() {<br> const { wallet } = useWallet();<br> const { needsAuth, sendEmailWithOtp, verifyOtp } = useWalletEmailSigner();<br> <br> const [recipientAddress, setRecipientAddress] = useState(&quot;&quot;);<br> const [sendAmount, setSendAmount] = useState(&quot;&quot;);<br> const [isModalVisible, setIsModalVisible] = useState(false);<br> const [isVerifying, setIsVerifying] = useState(false);<br> const [otpError, setOtpError] = useState(null);<br>const handleTransfer = async () =&gt; {<br> if (!recipientAddress || !sendAmount) {<br> Alert.alert(&quot;Error&quot;, &quot;Please enter both recipient address and amount.&quot;);<br> return;<br> }<br>try {<br> if (needsAuth) {<br> // If auth is needed, send the OTP email<br> await sendEmailWithOtp();<br> // Show the modal for the user to enter the OTP<br> setIsModalVisible(true);<br> } else {<br> // If no auth is needed, proceed with the transfer directly<br> const result = await wallet.send(recipientAddress, &#39;usdc&#39;, sendAmount);<br> Alert.alert(&quot;Success&quot;, &quot;Transfer completed successfully!&quot;);<br> }<br> } catch (error) {<br> Alert.alert(&quot;Error&quot;, error.message || &quot;An unknown error occurred.&quot;);<br> }<br> };<br>// Rest of the component…<br>}</pre><h4>Implementing OTP Verification</h4><p>Now, let’s implement the OTP verification modal and handle the verification process:</p><pre>const handleVerifyOtp = async (otpCode) =&gt; {<br> setIsVerifying(true);<br> setOtpError(null);<br> <br> try {<br> // First, verify the OTP to authenticate the session<br> await verifyOtp(otpCode);<br> <br> // If verification is successful, execute the actual transfer<br> const result = await wallet.send(recipientAddress, &#39;usdc&#39;, sendAmount);<br> Alert.alert(&quot;Success&quot;, &quot;Transfer completed successfully!&quot;);<br> setIsModalVisible(false);<br> } catch (error) {<br> setOtpError(error.message || &quot;Verification failed. Please try again.&quot;);<br> } finally {<br> setIsVerifying(false);<br> }<br>};</pre><h4>Creating the OTP Modal</h4><p>Here’s a simplified version of the OTP verification modal:</p><pre>export default function OtpVerificationModal({<br> visible,<br> onClose,<br> onVerify,<br> isVerifying,<br> error,<br>}) {<br> const [otp, setOtp] = useState(&#39;&#39;);<br>const handleVerifyPress = () =&gt; {<br> if (otp.trim()) {<br> onVerify(otp);<br> }<br> };<br>return (<br> &lt;Modal<br> transparent<br> animationType=&quot;none&quot;<br> visible={visible}<br> onRequestClose={onClose}<br> &gt;<br> &lt;View style={styles.backdrop}&gt;<br> &lt;TouchableOpacity style={styles.backdropTouchable} onPress={onClose} /&gt;<br> &lt;/View&gt;<br> <br> &lt;KeyboardAvoidingView<br> behavior={Platform.OS === &#39;ios&#39; ? &#39;padding&#39; : &#39;height&#39;}<br> style={styles.keyboardAvoidingView}<br> &gt;<br> &lt;View style={styles.modalContent}&gt;<br> &lt;Text style={styles.title}&gt;Verify Your Email&lt;/Text&gt;<br> &lt;Text style={styles.subtitle}&gt;<br> We&#39;ve sent a 6-digit code to your email. Please enter it below.<br> &lt;/Text&gt;<br> <br> &lt;TextInput<br> style={[styles.input, error ? styles.inputError : null]}<br> placeholder=&quot;000000&quot;<br> keyboardType=&quot;number-pad&quot;<br> maxLength={6}<br> value={otp}<br> onChangeText={setOtp}<br> autoFocus={visible}<br> editable={!isVerifying}<br> /&gt;<br> <br> {error &amp;&amp; &lt;Text style={styles.errorText}&gt;{error}&lt;/Text&gt;}<br> <br> &lt;View style={styles.buttonContainer}&gt;<br> &lt;TouchableOpacity<br> style={[styles.button, styles.cancelButton]}<br> onPress={onClose}<br> disabled={isVerifying}<br> &gt;<br> &lt;Text style={styles.cancelButtonText}&gt;Cancel&lt;/Text&gt;<br> &lt;/TouchableOpacity&gt;<br> <br> &lt;TouchableOpacity<br> style={[<br> styles.button,<br> styles.verifyButton,<br> (isVerifying || !otp.trim()) ? styles.buttonDisabled : null,<br> ]}<br> onPress={handleVerifyPress}<br> disabled={isVerifying || !otp.trim()}<br> &gt;<br> {isVerifying ? (<br> &lt;ActivityIndicator color=&quot;#fff&quot; /&gt;<br> ) : (<br> &lt;Text style={styles.verifyButtonText}&gt;Verify&lt;/Text&gt;<br> )}<br> &lt;/TouchableOpacity&gt;<br> &lt;/View&gt;<br> &lt;/View&gt;<br> &lt;/KeyboardAvoidingView&gt;<br> &lt;/Modal&gt;<br> );<br>}</pre><h4>Putting It All Together</h4><p>Now, let’s combine these pieces into a complete transfer component:</p><pre>export default function TokenTransfer() {<br> const { wallet } = useWallet();<br> const { needsAuth, sendEmailWithOtp, verifyOtp } = useWalletEmailSigner();<br> <br> const [recipientAddress, setRecipientAddress] = useState(&quot;&quot;);<br> const [sendAmount, setSendAmount] = useState(&quot;&quot;);<br> const [isModalVisible, setIsModalVisible] = useState(false);<br> const [isVerifying, setIsVerifying] = useState(false);<br> const [otpError, setOtpError] = useState(null);<br>const handleTransfer = async () =&gt; {<br> if (!recipientAddress || !sendAmount) {<br> Alert.alert(&quot;Error&quot;, &quot;Please enter both recipient address and amount.&quot;);<br> return;<br> }<br>try {<br> if (needsAuth) {<br> await sendEmailWithOtp();<br> setIsModalVisible(true);<br> } else {<br> const result = await wallet.send(recipientAddress, &#39;usdc&#39;, sendAmount);<br> Alert.alert(&quot;Success&quot;, &quot;Transfer completed successfully!&quot;);<br> }<br> } catch (error) {<br> Alert.alert(&quot;Error&quot;, error.message || &quot;An unknown error occurred.&quot;);<br> }<br> };<br>const handleVerifyOtp = async (otpCode) =&gt; {<br> setIsVerifying(true);<br> setOtpError(null);<br> <br> try {<br> await verifyOtp(otpCode);<br> const result = await wallet.send(recipientAddress, &#39;usdc&#39;, sendAmount);<br> Alert.alert(&quot;Success&quot;, &quot;Transfer completed successfully!&quot;);<br> setIsModalVisible(false);<br> } catch (error) {<br> setOtpError(error.message || &quot;Verification failed. Please try again.&quot;);<br> } finally {<br> setIsVerifying(false);<br> }<br> };<br>return (<br> &lt;View style={styles.container}&gt;<br> &lt;Text style={styles.title}&gt;Send Tokens&lt;/Text&gt;<br> <br> &lt;TextInput<br> style={styles.input}<br> placeholder=&quot;Recipient Address&quot;<br> value={recipientAddress}<br> onChangeText={setRecipientAddress}<br> /&gt;<br> <br> &lt;TextInput<br> style={styles.input}<br> placeholder=&quot;Amount&quot;<br> value={sendAmount}<br> onChangeText={setSendAmount}<br> keyboardType=&quot;numeric&quot;<br> /&gt;<br> <br> &lt;TouchableOpacity style={styles.sendButton} onPress={handleTransfer}&gt;<br> &lt;Text style={styles.sendButtonText}&gt;Send&lt;/Text&gt;<br> &lt;/TouchableOpacity&gt;<br> <br> &lt;OtpVerificationModal<br> visible={isModalVisible}<br> onClose={() =&gt; setIsModalVisible(false)}<br> onVerify={handleVerifyOtp}<br> isVerifying={isVerifying}<br> error={otpError}<br> /&gt;<br> &lt;/View&gt;<br> );<br>}</pre><p>You’ve written the code, now it’s time to run it.</p><pre>bun expo start</pre><h4>Key Takeaways</h4><p>1. OTP Verification is Required for Email Signers: When using email authentication, Crossmint requires OTP verification for security purposes. This wasn’t immediately clear in the documentation, so I hope this saves you some time!</p><p>2. Error Handling is Crucial: Make sure to implement proper error handling for both the OTP sending and verification processes.</p><p>3. User Experience Matters: Consider adding loading states and clear error messages to guide users through the OTP verification process.</p><p>4. Testing is Essential: Use testnet faucets to fund your wallet during development, and thoroughly test the OTP flow before deploying to production.</p><h4>What’s Next?</h4><p>While I’ve covered the basics of integrating Crossmint into a Expo application, there’s still more to explore:</p><p>- Implementing passkey authentication (I’m working on this myself!)<br>- Adding support for different blockchain networks<br>- Implementing transaction history<br>- Building a more robust error handling system</p><p>I hope this guide helps you navigate the Crossmint integration process more smoothly than my initial journey. Remember, the key is to understand the authentication flow and implement proper error handling throughout the process.</p><p>Happy coding, and may your transactions always confirm on the first try!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=68b8e51341d5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fixing Redux Persist Errors: Handling Non-Serializable Values]]></title>
            <link>https://claremburu.medium.com/fixing-redux-persist-errors-handling-non-serializable-values-fe625494f9bc?source=rss-14ed3a31edab------2</link>
            <guid isPermaLink="false">https://medium.com/p/fe625494f9bc</guid>
            <dc:creator><![CDATA[Clare Mburu]]></dc:creator>
            <pubDate>Fri, 01 Nov 2024 09:32:19 GMT</pubDate>
            <atom:updated>2024-11-01T09:32:19.812Z</atom:updated>
            <content:encoded><![CDATA[<p>As a developer working with Redux and Redux Toolkit, you may have encountered the error “A non-serializable value was detected in an action”. This error typically occurs when trying to store non-serializable data in your Redux state using Redux Persist. Let’s dive into what causes this error and how to fix it.</p><h4>Understanding the Error</h4><p>The error looks like this:</p><blockquote>index.js:1446 A non-serializable value was detected in an action, in the path: `register`. Value: ƒ register(key) {<br> _pStore.dispatch({<br> type: _constants__WEBPACK_IMPORTED_MODULE_2__[“REGISTER”],<br> key: key<br> });<br> }</blockquote><p>The error occurs when Redux Persist tries to serialize your state during persistence or rehydration. By default, Redux Toolkit includes a serializable check middleware that prevents non-serializable values from being stored in the state.</p><h4>Common Causes</h4><p>There are several reasons why this error might occur:</p><p>1. Using non-serializable values in your state (like functions or undefined)</p><p>2. Including actions or reducers in your state</p><p>3. Using complex objects or functions as keys in your state</p><h4>Solution</h4><p>The most straightforward way to fix this error is to disable the serializable check middleware like this in your redux store:</p><pre>import { configureStore } from &#39;@reduxjs/toolkit&#39;;<br>import { persistReducer } from &#39;redux-persist&#39;;<br><br>const persistConfig = {<br>  key: &#39;root&#39;,<br>  storage: storage,<br>};<br><br>const persistedReducer = persistReducer(persistConfig, rootReducer);<br><br>export default configureStore({<br>  reducer: persistedReducer,<br>  middleware: (getDefaultMiddleware) =&gt;<br>    getDefaultMiddleware({<br>      serializableCheck: false,<br>    }),<br>});</pre><p>However, this solution did not work for me. To fix this error, I modified my Redux Toolkit configuration to exclude certain actions from the serializable check. Here’s how you can do it:</p><pre>import { configureStore, createReducer } from &#39;@reduxjs/toolkit&#39;;<br>import { errorLoggingMiddleware } from &#39;@app/store/middlewares/errorLogging.middleware&#39;;<br>import rootReducer from &#39;@app/store/slices&#39;;<br>import { apiSlice } from &#39;@app/slices/apiSlice&#39;;<br>import authReducer from &#39;@app/slices/authSlice&#39;;<br>import { FLUSH, PAUSE, PERSIST, persistReducer, PURGE, REGISTER, REHYDRATE } from &#39;redux-persist&#39;;<br><br><br>import * as authActions from &#39;@app/slices/authSlice&#39;;<br>import storage from &#39;redux-persist/lib/storage&#39;;<br><br>const persistConfig = {<br>  key: &#39;root&#39;,<br>  storage,<br>};<br><br>const persistedReducer = persistReducer(persistConfig, authReducer);<br><br><br>const apiMiddleware = apiSlice.middleware;<br><br><br>const combinedReducers = {<br>  ...rootReducer,<br>  [apiSlice.reducerPath]: apiSlice.reducer,<br>  auth: persistedReducer,<br>  <br>};<br><br>export const store = configureStore({<br>  reducer: combinedReducers,<br>  middleware: (getDefaultMiddleware) =&gt;<br>    getDefaultMiddleware({<br>      serializableCheck: {<br>        ignoredPaths: [&#39;pwa.event&#39;],<br>        ignoredActions: [&#39;pwa/addDeferredPrompt&#39;, FLUSH, REHYDRATE, PAUSE, PERSIST, PURGE, REGISTER],<br>      },<br>    }).concat(errorLoggingMiddleware)<br>    .concat(apiMiddleware),<br>    devTools: true<br>});<br><br>export type RootState = ReturnType&lt;typeof store.getState&gt;;<br>export type AppDispatch = typeof store.dispatch;</pre><h4>What does the solution do?</h4><p>1. The `ignoredActions` array in the `serializableCheck` configuration tells Redux Toolkit to ignore certain actions during the serializable check.</p><p>2. We’re ignoring the standard Redux Persist actions (`FLUSH`, `REHYDRATE`, `PAUSE`, `PERSIST`, `PURGE`, `REGISTER`) along with any potential custom actions related to Redux Persist.</p><h4>Conclusion</h4><p>By applying these changes to your Redux Toolkit configuration, you should be able to resolve the non-serializable value error when using Redux Persist. This solution maintains the benefits of Redux Toolkit’s built-in middleware while allowing Redux Persist to work seamlessly with your application.</p><p>Remember, while this solution resolves the immediate error, it’s crucial to maintain a clean and serializable state structure throughout your application. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fe625494f9bc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My Journey with CORS Errors in Redux Toolkit]]></title>
            <link>https://claremburu.medium.com/my-journey-with-cors-errors-in-redux-toolkit-e1b94b19d05b?source=rss-14ed3a31edab------2</link>
            <guid isPermaLink="false">https://medium.com/p/e1b94b19d05b</guid>
            <dc:creator><![CDATA[Clare Mburu]]></dc:creator>
            <pubDate>Fri, 01 Nov 2024 08:48:04 GMT</pubDate>
            <atom:updated>2024-11-01T08:48:04.732Z</atom:updated>
            <content:encoded><![CDATA[<p>I was working on a React application using Redux Toolkit, when I recently found myself stuck on a pesky CORS issue. It was one of those frustrating moments where everything else seemed to be working fine, but suddenly my API calls were blocked due to cross-origin restrictions. Let me share my experience and how I resolved this issue.</p><h3>The Problem</h3><p>I was building a feature that required fetching data from an external API. My React components were using Redux Toolkit’s Query hooks to make these requests. Everything was working fine during development, but when I deployed to production, I started seeing CORS errors in the console.</p><p>Here’s what the error looked like:</p><blockquote>Access to fetch at ‘<a href="https://api.example.com/data&#39;">https://api.example.com/data&#39;</a> from origin ‘<a href="http://localhost:3000&#39;">http://localhost:3000&#39;</a> has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.</blockquote><p>At first, I thought it was just a matter of configuring my backend to allow CORS requests. But after digging deeper, I realized that Redux Toolkit’s Query hooks were actually sending OPTIONS preflight requests, which were being blocked by the CORS policy.</p><h3>The Solution</h3><p>After researching and experimenting, I found a few key things that helped me resolve the issue:</p><p>1. Configure fetchBaseQuery correctly:</p><p>Make sure you’re using the `mode: ‘cors’` option when initializing fetchBaseQuery:</p><pre>import { fetchBaseQuery } from &quot;@reduxjs/toolkit/query/react&quot;;<br><br>const baseQuery = fetchBaseQuery({<br> baseUrl: API_BASE_URL,<br> mode: &#39;cors&#39;,<br> });</pre><p>2. Set appropriate headers:</p><p>Add necessary headers to your requests, especially the ‘Accept’ header:</p><pre>import { fetchBaseQuery } from &quot;@reduxjs/toolkit/query/react&quot;;<br><br>const baseQuery = fetchBaseQuery({<br> baseUrl: API_BASE_URL,<br> mode: &#39;cors&#39;,<br> prepareHeaders: (headers) =&gt; {<br> headers.set(&quot;authorization&quot;, `Bearer ${token}`);<br> headers.set(&quot;Accept&quot;, &quot;application/json&quot;);<br> return headers;<br> },<br> });</pre><p>3. Use credentials: ‘include’:</p><p>If you need to include cookies or authentication tokens, use:</p><pre>import { fetchBaseQuery } from &quot;@reduxjs/toolkit/query/react&quot;;<br><br>const baseQuery = fetchBaseQuery({<br> baseUrl: API_BASE_URL,<br> mode: &#39;cors&#39;,<br>credentials: &#39;include&#39;,<br> prepareHeaders: (headers) =&gt; {<br> headers.set(&quot;authorization&quot;, `Bearer ${token}`);<br> headers.set(&quot;Accept&quot;, &quot;application/json&quot;);<br> return headers;<br> },<br> });</pre><p>4. Handle CORS errors gracefully:</p><p>Wrap your API calls in a try-catch block to handle CORS errors:</p><pre>try {<br> const result = await apiSlice.endpoints.getUsers.initiate();<br> } catch (error) {<br> console.error(&#39;CORS error:&#39;, error.message);<br> // Handle the error appropriately<br> }</pre><p>5. Check backend configuration:</p><p>Ensure your backend is configured to accept CORS requests from your frontend domain.</p><h4>Example in <em>Nodejs</em>:</h4><pre>const app = express();<br>app.use(cors({<br>  origin: [&quot;http://localhost:3000&quot;],<br>  credentials:true,<br>  methods: [&quot;GET&quot;, &quot;POST&quot;, &quot;PUT&quot;, &quot;DELETE&quot;,&quot;PATCH&quot;],<br>  allowedHeaders: [&quot;Content-Type&quot;, &quot;Authorization&quot; ],<br>  optionsSuccessStatus: 200,<br>})); </pre><p>My Personal Experience</p><p>After implementing these changes, I was thrilled to see that my CORS issues were resolved. The API calls started working smoothly in both development and production environments.</p><p>However, I quickly realized that CORS isn’t just about fixing errors — it’s also about understanding why they happen and how to secure your application. Here are some takeaways from my experience:</p><p>- Always test your CORS setup thoroughly in both development and staging environments.<br>- Remember that CORS policies are enforced by browsers, not servers. Your server needs to explicitly allow cross-origin requests.<br>- When using Redux Toolkit, pay attention to how Query hooks handle preflight requests and adjust your configuration accordingly.<br>- Don’t forget to handle CORS errors gracefully in your application to provide a better user experience.</p><h4>Conclusion</h4><p>While CORS errors can be frustrating, they often lead to valuable learning experiences. By diving deep into the issue and exploring different solutions, I gained a deeper understanding of how web security works and how to build robust APIs.</p><p>If you’re facing similar CORS issues with Redux Toolkit, I encourage you to experiment with these solutions. Remember, every developer faces challenges like this at some point, and sharing our experiences can help others avoid similar pitfalls.</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e1b94b19d05b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Migrating from JWT to PASETO: Why I Made the Switch]]></title>
            <link>https://claremburu.medium.com/migrating-from-jwt-to-paseto-why-i-made-the-switch-87ed51c020d3?source=rss-14ed3a31edab------2</link>
            <guid isPermaLink="false">https://medium.com/p/87ed51c020d3</guid>
            <dc:creator><![CDATA[Clare Mburu]]></dc:creator>
            <pubDate>Fri, 01 Nov 2024 08:29:45 GMT</pubDate>
            <atom:updated>2024-11-01T08:29:45.393Z</atom:updated>
            <content:encoded><![CDATA[<p>I’ve recently made the switch from using JSON Web Tokens (JWT) to Platform-Agnostic Security Tokens (PASETO) v4 for authentication in web applications. This decision wasn’t easy, but after careful consideration of the pros and cons, I believe PASETO offers significant advantages over JWT. Let me walk you through the reasons behind this migration and provide some code examples to illustrate the differences.</p><h3>Understanding JWT Limitations</h3><p>Before diving into PASETO, let’s briefly review some limitations of JWT:</p><p>1. Weak algorithms: JWT offers many signing algorithms, some of which are known to be vulnerable.</p><p>2. Trivial forgery: JWT’s structure makes it easy for attackers to bypass signature verification.</p><p>3. No encryption: JWT payloads are only base64-encoded, not encrypted.</p><p>4. Algorithm negotiation: JWT includes the signing algorithm in the token header, allowing potential attacks.</p><h3>Introducing PASETO</h3><p>PASETO addresses these issues and provides a more secure and straightforward approach to token-based authentication.</p><h3>Why Migrate from JWT to PASETO v4?</h3><h4>Enhanced Security</h4><p>One of the primary reasons for migrating to PASETO v4 is its improved security profile compared to JWT.</p><p>- No Algorithm Negotiation: PASETO prevents downgrade attacks by specifying the cryptographic algorithm upfront .</p><p>- Mandatory Authentication: All tokens in PASETO require mandatory authentication, enhancing overall security.</p><p>- Built-in Support for Encrypted Tokens: PASETO provides native support for encrypted tokens, offering an extra layer of protection.</p><h3>Implementation Example</h3><p>Let’s compare JWT and PASETO implementations in Node.js:</p><h4>JWT Implementation</h4><pre>import jwt from &#39;jsonwebtoken&#39;;<br><br>// Creating a JWT<br>function createToken(payload) {<br>  return jwt.sign(payload, &#39;your-secret-key&#39;, { expiresIn: &#39;1h&#39; });<br>}<br><br>// Verifying a JWT<br>function verifyToken(token) {<br>  try {<br>    return jwt.verify(token, &#39;your-secret-key&#39;);<br>  } catch (error) {<br>    console.error(&#39;Token verification failed:&#39;, error.message);<br>    return null;<br>  }<br>}<br><br>// Usage<br>const payload = { userId: 123, username: &#39;johndoe&#39; };<br>const token = createToken(payload);<br>console.log(&#39;Created JWT:&#39;, token);<br><br>verifyToken(token).then(decoded =&gt; {<br>  console.log(&#39;Decoded JWT:&#39;, decoded);<br>}).catch(err =&gt; {<br>  console.error(&#39;Invalid JWT:&#39;, err.message);<br>});</pre><h4>PASETO Implementation</h4><pre>import * as paseto from &#39;paseto&#39;;<br>import UserToken from &quot;../models/tokenModel.js&quot;;<br>import { getkgenOne } from &#39;../controllers/tokenController.js&#39;;<br><br>const { V4 } = paseto;<br>const { sign, verify,generateKey } = V4;<br><br>// Function to generate keys<br>async function generateKeyPair2() {<br>  const genkey = await generateKey(&#39;public&#39;,{&#39;format&#39;:&#39;paserk&#39;});<br>  return { genkey };<br>}<br><br>const aw = await generateKeyPair2()<br><br>// Helper function to sign tokens<br>async function signToken(payload) {<br>  const prk1 = aw.genkey.secretKey<br><br>    // Calculate expiration time for 1 hour from now<br>  const expTime = Math.floor(Date.now() / 1000) + 3600;<br><br>    // Add exp claim to the payload<br>  payload.exp = expTime.toString();<br><br>  return await sign(payload, prk1 );<br>}<br><br>const generateToken = async(res, userId)=&gt;{<br><br>  const payload = {userId}<br>  const jsonString = JSON.stringify(payload);<br>  const buffer = Buffer.from(jsonString, &#39;utf8&#39;);<br>  const token = await signToken(buffer);<br>  return token;<br><br>}<br><br>// Generate Token<br>const genToky = async(res, userId) =&gt;{<br>  try {<br>    const privateKey1 = aw.genkey.secretKey<br>    const publicKey1 = aw.genkey.publicKey<br><br>    const token = await generateToken(res, userId)<br><br>    const ptkgen1 = new UserToken({<br>      userId:userId,<br>      token:token,<br>      privateKey:privateKey1,<br>      publicKey:publicKey1,<br>    <br>    });<br>    <br>    const ptkgen2 = await ptkgen1.save()<br><br>    return {publicKey1,privateKey1,token}<br><br>    <br>  } catch (error) {<br>    console.error(error)<br>  }<br>  return null; // Return null if an error occurs<br>}<br><br>// Verify Token<br>const verTok = async(token)=&gt;{<br>    <br>  const pk1 = aw.genkey.publicKey<br><br>  // Verify the PASETO token<br>  const decoded = await verify(token, pk1);<br><br>  return decoded<br>}<br><br>export {genToky,verTok}; <br><br><br>// Usage Example<br><br><br>// Protect Middleware<br><br>import asyncHandler from &#39;./asyncHandler.js&#39;;<br>import User from &#39;../models/userModel.js&#39;;<br>import { verTok } from &#39;../utils/generateToken.js&#39;;<br><br>const protect = asyncHandler(async (req, res, next) =&gt; {<br><br>  const authHeader = req.headers.authorization;<br>  <br>  if (!authHeader || !authHeader.toLowerCase().startsWith(&#39;bearer &#39;)) {<br>    console.error(&#39;Invalid authorization header&#39;);<br>    return res.status(401).json({ error: &#39;No token provided&#39; });<br>  }<br><br>  const token = authHeader.split(&#39; &#39;)[1];<br><br>  if (!token) {<br>    console.error(&#39;Token not found after splitting&#39;);<br>    return res.status(401).json({ error: &#39;No token provided&#39; });<br>  }<br><br>  try {<br>    const decoded = await verTok(token)<br><br>    // Get the user ID from the payload<br>    const userId = decoded;<br>    const user = await User.findOne(userId).select(&#39;-password&#39;);<br><br>    if (!user) {<br>      throw new Error(&#39;User not found&#39;);<br>    }<br><br>    req.user = user;<br>    next();<br>  } catch (error) {<br>    console.error(&#39;PASETO verification failed:&#39;, error.message);<br>    if (error.name === &#39;InvalidTokenError&#39;) {<br>      return res.status(401).json({ error: &#39;Invalid token&#39; });<br>    }<br>    return res.status(500).json({ error: &#39;Internal Server Error&#39; });<br>  }<br>});<br><br>export { protect};</pre><h3>Benefits of Migrating to PASETO V4</h3><p>1. Enhanced Security: PASETO addresses many common JWT vulnerabilities out of the box.</p><p>2. Simplicity: With fewer options to choose from, PASETO reduces the risk of misconfiguration.</p><p>3. Future-proofing: PASETO uses modern cryptographic primitives, ensuring better long-term security.</p><p>4. Flexibility: While PASETO offers built-in encryption, it also supports custom payloads and formats.</p><h3>Conclusion</h3><p>I believe the enhanced security features and simplified implementation of PASETO outweigh the migration efforts. However, the choice between JWT and PASETO should ultimately depend on your project requirements, existing infrastructure, and security needs.</p><p>If you’re building a new project or considering upgrading from JWT, I highly recommend exploring PASETO v4 as a secure and simpler alternative.</p><p>Remember, security is an ongoing process. Regularly review and update your authentication methods to ensure they align with current best practices and evolving threats.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=87ed51c020d3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Fetch data from an API in React]]></title>
            <link>https://claremburu.medium.com/how-to-fetch-data-from-an-api-in-react-d4f20f6e11c9?source=rss-14ed3a31edab------2</link>
            <guid isPermaLink="false">https://medium.com/p/d4f20f6e11c9</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[useeffect]]></category>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[fetch-api]]></category>
            <dc:creator><![CDATA[Clare Mburu]]></dc:creator>
            <pubDate>Mon, 12 Jul 2021 04:50:11 GMT</pubDate>
            <atom:updated>2021-07-12T16:36:20.516Z</atom:updated>
            <content:encoded><![CDATA[<p>Fetching data from an API can be done in so many ways. In this tutorial, we will use the Fetch API to fetch data from an external API. Fetch is a promise-based inbuilt browser API that is used to make HTTP requests from endpoints.</p><p>For this tutorial, we will fetch data from <a href="https://jsonplaceholder.typicode.com/">this</a> URL and list it in a simple table. You can as well use your JSON API that you can connect to to fetch data.</p><p>This tutorial assumes that you have prior knowledge in React Hooks, UseEffect lifecycle method, promises, APIs and handling events in Javascript. All the code will be provided on <a href="https://github.com/claremburu/Fetch-API">Github</a>.</p><p>Lets jump in!</p><p><strong>When the component mounts</strong></p><p>This involves sending a http request to an api then displaying the data to a browser. We will handle the loading state before the data is fetched in our API.</p><p>When our component mounts, we need to know whether we’ve fetched the data or we’ve completed fetching data. We will set the default loading state to false. We will show some loading indicator and then fetch the data using the useEffect hook.</p><p>When useEffect is called, we get the data from the response and then we update the state. The data will render twice. Once for the initial loading state, then a second time with the new posts data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/25644e1d0482883b3433ddd62023230f/href">https://medium.com/media/25644e1d0482883b3433ddd62023230f/href</a></iframe><p><strong>Handling Events</strong></p><p>The response will be in JSON format. We will create two tables where one will render the posts data while the other will render the comments of the posts.</p><p>In order to display the posts in a table, we will need to filter the posts data based on a specific user Id. This means that when we click the user id, it should create a new table that shows the posts of that user.</p><p>For the comments table, we will need to filter the comments data based on a specific posts id. This means that when we click the post id, it should create a new table that shows comments of that post.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/249d43e35fc74331694463fefc1214aa/href">https://medium.com/media/249d43e35fc74331694463fefc1214aa/href</a></iframe><p><strong>Conclusion</strong></p><p>Fetch will allows us to make the http requests to get data from an endpoint. It renders first by saying loading. When the useEffect gets called , we fetch the data from the endpoint, we get the data from response and then we update the state.</p><p>React offers multiple ways to fetch data from an API. I hope I shed some light on how to effectively fetch data from an external API using the fetch API.</p><p>Thank you for reading my blog. Want to share some thoughts? Feel free to reach out to me via <a href="https://www.linkedin.com/in/claremburu/">LinkedIn</a> and <a href="https://twitter.com/Mburuclare">Twitter</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d4f20f6e11c9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to visualize data from a CSV file in React(Full code on Github)]]></title>
            <link>https://claremburu.medium.com/how-to-visualize-data-from-a-csv-file-in-react-full-code-on-github-258897516be2?source=rss-14ed3a31edab------2</link>
            <guid isPermaLink="false">https://medium.com/p/258897516be2</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[line-graph]]></category>
            <category><![CDATA[csv-file]]></category>
            <category><![CDATA[highcharts]]></category>
            <category><![CDATA[react-hook]]></category>
            <dc:creator><![CDATA[Clare Mburu]]></dc:creator>
            <pubDate>Sun, 04 Jul 2021 12:42:00 GMT</pubDate>
            <atom:updated>2021-07-05T11:00:58.982Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xhUqg6ejHh81tN2ANO_qtw.png" /><figcaption>Photo by <a href="https://unsplash.com/@claremburu">Clare Mburu</a> on <a href="https://unsplash.com/">Unsplash</a></figcaption></figure><p>A CSV is a Comma Separated Value file that stores tables data. In this step-by-step tutorial, we will be generating a line graph given a simple CSV file.</p><p>The prerequisites for this tutorial are knowledge in: React Hooks, Arrays and ES6.All the code is provided on <a href="https://github.com/claremburu/Line-Graph">Github</a>. Incase of comments or questions contact me on my <a href="https://www.linkedin.com/in/claremburu/">social media handles </a>or via email.</p><p>To start with, lets create a simple CSV file using the following data:</p><p><em>date, amount, spent</em></p><p><em>2019–01–01, 10, 100</em></p><p><em>2019–01–02, 20, 200</em></p><p>You can as well use your own values for date, amount and spent.</p><p>Now that we’ve created a simple CSV file, lets create a textbox where we will paste our simple CSV file content.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9e2ded6e3b1d3aeb85fe613921bbb907/href">https://medium.com/media/9e2ded6e3b1d3aeb85fe613921bbb907/href</a></iframe><h3>Converting a CSV string to an array</h3><p>To parse data in a CSV file, we will need to import a csv library.</p><pre>import * as CSV from &quot;csv-string&quot;;</pre><h3>Process the data</h3><p>At this point, we will need a button to read the CSV data pasted in the textarea. When the button is clicked, it should automatically read the headers(date, amount, spent) and put those variables in the dropdown box.</p><p>In order to connect data points in a line graph, we will need to generate values for the horizontal axis(X-axis) and vertical axis(Y-axis). For this, we will create two drop down boxes for the X and Y axis to populate the column names(date, amount, spent).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/781363cf9641b41f19260bee59ff5d77/href">https://medium.com/media/781363cf9641b41f19260bee59ff5d77/href</a></iframe><p>The idea is to get headers(date, amount, spent) from the CSV file, remove them from the list and update the array with the other array values.</p><p>The array provided is a nested array. This means that we need to iterate through the array to get the header values, then get the values of the array with the same index as the header and push the new array items to the new list(refinedList) in this case.</p><p>With that in mind, lets break it down.</p><ol><li>Parse CSV string into an array.</li><li>Get the headers from the list(date, time, spent)</li><li>Remove the headers from the list.</li><li>Get the values for each column, i.e. the headers and return their values(date=[0], amount=[1], spent=[2]).</li><li>Get items from the array with the same index as the header(<em>date is at index 0 which means that 2019–01–01 is at index 0</em>).</li><li>Push the array items to the columns of the new array.</li><li>Update the state of the array.</li></ol><p>The dropdown boxes should now contain all the column values(date, amount, spent). To illustrate our array items, we will add a button that will generate a line graph when the values in the X and Y axis are selected.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a0b5ace708485b7af00674240c55ab9d/href">https://medium.com/media/a0b5ace708485b7af00674240c55ab9d/href</a></iframe><h3>Line Graph</h3><p>Finally, we will use highcharts to generate our simple line graph. Highcharts is a javascript library for creating interactive charts that can be used in your web projects. I encourage you to explore <a href="https://www.highcharts.com/">this</a> library since it is efficient and easy to configure and use.</p><p>The following code shows how easy it is to visualize our array data using highCharts.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b1456059582aaeb05c65021cb8f5ce0f/href">https://medium.com/media/b1456059582aaeb05c65021cb8f5ce0f/href</a></iframe><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/841/1*tVmpodoLvL1Ab7nv42l_JA.png" /></figure><p>I’m glad you made it this far!. Share your thoughts below. Happy hacking!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=258897516be2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>