<?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 Syed M Ahmad on Medium]]></title>
        <description><![CDATA[Stories by Syed M Ahmad on Medium]]></description>
        <link>https://medium.com/@syedmahmad?source=rss-83a494cbe898------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*5HjGHGf54MHfaZVKhFZbag.jpeg</url>
            <title>Stories by Syed M Ahmad on Medium</title>
            <link>https://medium.com/@syedmahmad?source=rss-83a494cbe898------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 16:48:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@syedmahmad/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[Facebook Login Integration in React (2024 Edition)]]></title>
            <link>https://medium.com/@syedmahmad/login-with-facebook-meta-in-react-app-88efb7a9fc0a?source=rss-83a494cbe898------2</link>
            <guid isPermaLink="false">https://medium.com/p/88efb7a9fc0a</guid>
            <category><![CDATA[react-facebook-login]]></category>
            <category><![CDATA[login-with-facebook]]></category>
            <category><![CDATA[facebook]]></category>
            <category><![CDATA[reactjs]]></category>
            <dc:creator><![CDATA[Syed M Ahmad]]></dc:creator>
            <pubDate>Wed, 03 Apr 2024 11:18:40 GMT</pubDate>
            <atom:updated>2024-04-03T11:26:21.902Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pqX7sDMMTYYEvQDgp1LTpw.jpeg" /></figure><p>In this post, we will cover challenges developers usually face while integrating facebook/meta login in react.js apps.</p><h4>Prerequisite:</h4><ul><li>react application already setup and running.</li><li>You may either install `react-facebook` OR `react-facebook-login` whatever you would like to use.</li><li>set up a Facebook App</li><li>set up openssl for local testing in case you face this issue.</li></ul><h4>Let’s get started:</h4><p>We will not focus on react application setup as this is easy and anyone who is landed to this post have already setup the app and struggling with facebook login. So, let’s focus on the problem.</p><p>You need to install npm module for facebook login. In this blog, I choose react-facebook-login.</p><ul><li>npm i react-facebook-login</li><li>if you get any errors, it means, you are on latest version of react, so please run any of these.</li></ul><pre>npm install react-facebook-login -S --force<br><br>npm install react-facebook-login -S --legacy-peer-deps</pre><p>Once this install, you have simple steps.</p><pre>import React from &#39;react&#39;;<br>import FacebookLogin from &#39;react-facebook-login&#39;;<br><br>const LoginForm = (props) =&gt; {<br>  const handleFacebookCallback = (response) =&gt; {<br>    if (response?.status === &quot;unknown&quot;) {<br>        console.error(&#39;Sorry!&#39;, &#39;Something went wrong with facebook Login.&#39;);<br>     return;<br>    }<br>    console.log(response);<br>      // console will print following object for you.<br>        {<br>          &quot;name&quot;: &quot;Syed M Ahmad&quot;,<br>          &quot;email&quot;: &quot;ssgcommando90@yahoo.com&quot;,<br>          &quot;picture&quot;: {<br>              &quot;data&quot;: {<br>                  &quot;height&quot;: 50,<br>                  &quot;is_silhouette&quot;: false,<br>                  &quot;url&quot;: &quot;https://platform-lookaside.fbsbx.com/platform/profilepic/?asid=7138203302951151&amp;height=50&amp;width=50&amp;ext=1714730459&amp;hash=AfplSQ-UxV9LeHd5wYnaKbeKEIfUjMN-pHFGZJaWwC-00g&quot;,<br>                  &quot;width&quot;: 50<br>              }<br>          },<br>          &quot;id&quot;: &quot;7138203302951151&quot;,<br>          &quot;userID&quot;: &quot;7138203302951151&quot;,<br>          &quot;expiresIn&quot;: 7142,<br>          &quot;accessToken&quot;: &quot;EAANdCvUejTUBO3C5uZCp0n6i9H31bCdW6bZBUcOET2aTbWlZCJA7kQoQ1jxDCsnFctxZBAQPl2kSUSqb4N6KDLM8wROXn4fZCBj1Pmgq5peKkmPv7YJWHKXLb9mOIwcBbJJGj5EaXwLURktOGSv7HeNsiGxZBPBr1jewzZAL7FxbITljSsBq6LYnhKO6xT9D5FbFZB1JWdjii63xAeU36wZDZD&quot;,<br>          &quot;signedRequest&quot;: &quot;r3tHehW5aounQcMzalAtmiHR_lCmRHy0GSmrlD4w3zM.eyJ1c2VyX2lkIjoiNzEzODIwMzMwMjk1MTE1MSIsImNvZGUiOiJBUURUaEItZ3Z6RjViN09yV3VyM2tOai1FdDNQM1NGSHpheWVsMEYxSXc1NTNlTHBoZUs3M2RtTENFbVZTVjgySEZlUUFCQ0dPR19zME94RjU4LS14MFYxUWZIYkhCdDFTVl9FNG1scnh6Y2Z5RTVFNVozUy03SllRWUI2MEh1bW15b19mN3FKc3pLZENSbWFBbkE2c3JXenBCYnRfLXZIVTZjRTNYSjZnN19Db2xXNjk0Z1JDODd5eVVjT2R4NEszMHY4LXdrVlpVQWNvMXBkZGR1eTVqbFN4Yld0RkhGVlNpS282OGZxc09YdndYSXlDR0NOTjJrZEhDUDJSZElkT3VmSmRhbGs0dEo1TTRFUU9nWXJ3QllkeVlyUlY1ZlRuS3RvdGJyMF9ROHpQT21PTzQ2eXNBZmtJdGdjblFjOG5VaHQ5U0RMRlAzRVBhS0Q0dV9mY0YwbyIsImFsZ29yaXRobSI6IkhNQUMtU0hBMjU2IiwiaXNzdWVkX2F0IjoxNzEyMTM4NDU4fQ&quot;,<br>          &quot;graphDomain&quot;: &quot;facebook&quot;,<br>          &quot;data_access_expiration_time&quot;: 1719914458<br>      }<br>   }<br><br>  return (<br>    &lt;FacebookLogin <br>      buttonStyle={{padding:&quot;6px&quot;}}  <br>      appId=&quot;946726573608245&quot;  // we need to get this from facebook developer console by setting the app.<br>      autoLoad={false}  <br>      fields=&quot;name,email,picture&quot;  <br>      callback={handleFacebookCallback}/&gt;<br>  );<br>};<br>export default LoginForm;</pre><p>Let’s generate <strong>appId</strong> by creating new app in facebook developer console.</p><p>Here are the simple but important steps as you can see old version in many other blog posts but facebook have changes a little in UI.</p><p>1- You can go to facebook developer console and can click on create new app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vnOMkl-kDsYDElM3mCZx9Q.png" /></figure><p>2- You need to select below mentioned options and click next.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BTQAKHbbvcP4f3nQbq9eVw.png" /></figure><p>3- choose which applicaiton, you are trying to build.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4alzXVpoQLQOSfobhiKsXA.png" /></figure><p>4- Add app name, email and business if you have any.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HT7524RL-MGXxuaabr4cqg.png" /></figure><p>5- After successfully creation, you will see this screen</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S5YsF8pqVB6dy2KAZLjTbQ.png" /></figure><p>6- follow step1 and step2 as mentioned in screenshot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qKfpQXwvPSpEzW_dNLdKhg.png" /></figure><p>7- enable login with javascript SDK and add domain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*37Ngg09A3JyYcv3P_BYbzQ.png" /></figure><p>8- Your applicaiton is ready for testing. You can go to basic settings, copy appId and past it in your code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8zXBKrKel5ty2EP0Q8wGdw.png" /></figure><p>9- Before, app submission, you need to fulfil other requirements like app icon etc but not necessay for local testing.</p><p>10- Next and last step is to <strong>set up openssl</strong>, in case if anyonce face issue related <strong>secure local domain</strong>.</p><ul><li>Each system has its own requirements for generating the ssl certificates so, I am not cover that part here. but once you generate files, you just need to replace.</li></ul><pre>&quot;scripts&quot;: {<br>    &quot;start&quot;: &quot;react-scripts start&quot;,<br>    ...<br>  },<br><br>Replace it with<br><br>&quot;scripts&quot;: {<br>    &quot;start&quot;: &quot;export HTTPS=true&amp;&amp;SSL_CRT_FILE=../../openssl/public_key.pem&amp;&amp;SSL_KEY_FILE=../../openssl/private_key.pem react-scripts start&quot;,<br>    ....<br>  },</pre><p>You are good to go.</p><p>Hope all make sense if not, drop me a message on <a href="https://www.linkedin.com/in/syed-muhammad-ahmad-388006278/">Linkedin</a> OR <a href="https://www.buymeacoffee.com/syedmahmad">Buy me a cup of coffee</a></p><p>If you find this information valuable, please give it a thumbs up and consider following me for more updates.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=88efb7a9fc0a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Relay Mutations with fragments (Simplified)]]></title>
            <link>https://medium.com/@syedmahmad/relay-mutations-with-fragments-simplified-66eb075f4?source=rss-83a494cbe898------2</link>
            <guid isPermaLink="false">https://medium.com/p/66eb075f4</guid>
            <category><![CDATA[graphql-mutations]]></category>
            <category><![CDATA[relay]]></category>
            <category><![CDATA[relay-modern]]></category>
            <category><![CDATA[mutation-with-fragments]]></category>
            <category><![CDATA[relay-usemutation]]></category>
            <dc:creator><![CDATA[Syed M Ahmad]]></dc:creator>
            <pubDate>Wed, 13 Sep 2023 11:42:32 GMT</pubDate>
            <atom:updated>2023-09-13T11:42:32.815Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QejjlFQGX_Cf_mB7DECgTw.png" /></figure><p>This article is a segment of my “<a href="https://medium.com/@syedmahmad/956f33739f0">Simplified React Relay (modern)</a>” series. If you’re interested in understanding what React Relay is and how to seamlessly implement it in your applications, you’ve come to the right place. I’ve endeavored to encompass all the subjects with straightforward examples to ensure accessibility for everyone.</p><h3>Introduction</h3><p>Mutation is a <strong>read-write server operation</strong> that not only <strong>alters the data</strong> on the backend but also enables or allow you to query the modified data in the same request.</p><h3>How to create it</h3><p>In order to create a Mutation in Relay, we can use the useMutation and commitMutation API. We’ll cover it with useMutation hook as commitMutationAPI is relatively older way.</p><p>let’s dive into an example.</p><ul><li>We’re going to update user email info.</li><li>Within our operation, we incorporate both a mutation and a fragment spread. This allows us to update user fields and simultaneously send those updated fields back to the frontend. Additionally, we have the flexibility to include another fragment within the returned fields, optimizing data retrieval from the server in a single round trip.</li></ul><pre>import {graphql, useSubscription} from &#39;react-relay&#39;;<br>import {useMemo} from &#39;react&#39;;<br><br>const fragment = graphql`<br>  fragment updateEmailInfoFragment on mutation_root {<br>     user(<br>          where: {<br>              id: {_eq: $id}},<br>              _set: {<br>                  email: $email,<br>                  email_reminder: $reminder,<br>                  email_messages: $emailMsgs<br>              }<br>    ) {<br>      returning {<br>        email<br>        email_reminder<br>        email_messages<br>      }<br>    }<br>  }<br>`;<br><br>const UpdateEmailInfo = graphql`<br>  mutation EmailInfoMutation(<br>      $id: Int,<br>      $reminder: Int,<br>      $email: String,<br>      $emailMsgs: smallint<br>    ) {<br>      ...updateEmailInfoFragment<br>    }<br>  `;<br><br>function GroupLessonsContainer() {<br>  const [fragmentRef, setFragmentRef] = useState();<br>  const [EmailInfoMutationCommit, isMutationInFlight] = useMutation(UpdateEmailInfo);<br>    <br>  updateEmailInfo = () =&gt; {<br>    EmailInfoMutationCommit({<br>      variables: {<br>        id: 4,<br>        reminder: true,<br>        email: test@yahoo.com,<br>        emailMsgs: &#39;message here&#39;<br>      },<br>      onCompleted(res) {<br>        // here we will get the updated fragment Reference that we<br>        // can use in other components in useFragment hook to read<br>        // the data from relay store.<br>        setFragmentRef(res);<br>      },<br>      onError() {...},<br>      // Extras..... if you want<br>      // If an optimisticResponse (object that reflect your mutation output) is provided<br>      // it will update the relay store and all connected components to that relay store<br>      // (via fragments) will be updated, although, we did not get the mutation response<br>      // yet.<br>      // Once we get the response, relay store will again update based on the returned val.<br><br>      // there are 2 more fucntions.<br>      // 1: optimisticUpdater: it is a callback, Relay will execute it and update the<br>      //    store accordingly before we get the mutation response.<br>      // 2: updater: executes after the mutation request succeeds.<br>      // https://relay.dev/docs/guided-tour/updating-data/graphql-mutations/#order-of-execution-of-updater-functions<br>      optimisticResponse: {<br>        user: {<br>          returning: [<br>            {<br>              id: __id,<br>              email_reminder: data.email_reminder,<br>              email: data.email.trim(),<br>              email_messages: data.email_messages,<br>            }<br>          ]<br>        },<br>      },<br>      optimisticUpdater: () =&gt; {<br>        ...<br>      },<br>    });<br>  }<br><br>  return &lt;button onClick={updateEmailInfo}&gt; update user info &lt;/button&gt;<br>}</pre><p>You have noticed, we spread the <strong>fragment</strong> inside <strong>mutation</strong> that’s because, we always wanted to read data from fragments as we’re using here the relay best practices. On the other hand, if we don’t <strong>spread fragment inside mutation</strong> and wanted to read the returned fields directly in the <strong>onCompleted callback, </strong>then instead of fragment reference inside mutation, we can direct write the mutated fields inside mutation. In this way, we will not get fragment reference inside onComplete callback.</p><p>Hope all make sense if not, drop me a message on <a href="https://www.linkedin.com/in/syed-muhammad-ahmad-388006278/">Linkedin</a> OR <a href="https://www.buymeacoffee.com/syedmahmad">Buy me a cup of coffee</a></p><p>If you find this information valuable, please give it a thumbs up and consider following me for more updates.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=66eb075f4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Relay Subscriptions with fragments (Simplified)]]></title>
            <link>https://medium.com/@syedmahmad/relay-subscriptions-with-fragments-simplified-76489b6ebea0?source=rss-83a494cbe898------2</link>
            <guid isPermaLink="false">https://medium.com/p/76489b6ebea0</guid>
            <category><![CDATA[relay]]></category>
            <category><![CDATA[relay-subscri-fragments]]></category>
            <category><![CDATA[usesubscription-hook]]></category>
            <category><![CDATA[graphql-subscriptions]]></category>
            <category><![CDATA[relay-modern]]></category>
            <dc:creator><![CDATA[Syed M Ahmad]]></dc:creator>
            <pubDate>Tue, 12 Sep 2023 11:41:11 GMT</pubDate>
            <atom:updated>2023-09-12T11:58:13.735Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*NIz_alVSi-Zb3BGXIkGE7Q.jpeg" /></figure><p>This article is a segment of my “<a href="https://medium.com/@syedmahmad/956f33739f0">Simplified React Relay (modern)</a>” series. If you’re interested in understanding what React Relay is and how to seamlessly implement it in your applications, you’ve come to the right place. I’ve endeavored to encompass all the subjects with straightforward examples to ensure accessibility for everyone.</p><h3>Introduction</h3><p>Graphql subscription is a mechanism which allow <strong>clients</strong> to do query for data in response to a <strong>stream of server-side-events</strong>. It syntax looks similar to <strong>graphql query</strong>, only diff is, it uses the subscription keyword.</p><blockquote>Important Points: We can subscribe to anything using a “where” condition. This means that whenever our “where” condition is met, we receive a notification. So…</blockquote><ul><li>We can be notified if the data inserted, deleted or modified. The only point is our condition inside where clause should match.</li></ul><h4>How to create it</h4><p>In order to create a subscription in Relay, we can use the useSubscription and requestSubscription APIs. We’ll cover it with useSubscription hook as requestSubscription API is relatively older way.</p><p>This useSubscription hook takes 2 parameters.</p><ul><li>GraphQL literal containing the subscription</li><li>variables with which to establish the subscription</li></ul><p><strong>Caution</strong>: Obj passing inside useSubscription should be <strong>memoized</strong> Otherwise, useSubscription will dispose the subscription and re-establish it with every render!</p><ul><li>When hook <strong>commits</strong>, Relay will establish a subscription. Unlike the APIs like useLazyLoadQuery, Relay will <strong>not</strong> attempt to establish this subscription during the render phase.</li><li>Once connection established, whenever an event occurs, the backend will notify frontend. Relay will find a same object in the store with a matching id and update it with the newly received titlevalue.</li></ul><h3>Store Management:</h3><p>Based on the subscription connection, relay will auto manage the store and updated it. If we want more control then relay provide a way named as <strong>Imperatively modifying local data F</strong>or that, GraphQLSubscriptionConfig accepts an updaterfunction which gives you full control over how to update the store. In addition to updater We may want to execute a callback if an error is received or if the server ends the subscription. The GraphQLSubscriptionConfig can include the following fields to handle such cases:</p><ul><li>onNext, a callback that is executed when a subscription payload is received.</li><li>onError, a callback that is executed when the subscription errors.</li><li>onCompleted, a callback that is executed when the server ends the subscription.</li></ul><p>No more talking; let’s dive into an example.</p><ul><li>Need to get next 3 days group lessons.</li><li>Need notification in frontend if any of these lessons time updates etc.</li><li>Once, we get updated data in <strong>onNext callback, </strong>we update <strong>fragmentRef </strong>in react state which we are uisng in next component to reading data from relay store.</li></ul><pre>import {graphql, useSubscription} from &#39;react-relay&#39;;<br>import {useMemo} from &#39;react&#39;;<br><br>const fragment = graphql`<br>  fragment GroupLessonsFragment on subscription_root {<br>    appt_group_connection(<br>      where: {<br>        status: { _eq: &quot;0&quot; }<br>        ends_at: {_gt: $currentTime},<br>        starts_at: {_lt: $endTime}<br>      }<br>      order_by: { starts_at: asc }<br>    ) {<br>      edges {<br>        node {<br>          uuid<br>          starts_at<br>          ends_at<br>          minutes<br>          students<br>        }<br>      }<br>    }<br>  }<br>`;<br><br>const GroupLessonsSubscription = graphql`<br>  subscription scheduleGroupLessonsSubscription($currentTime: timestamptz, $endTime: timestamptz) {<br>    ...GroupLessonsFragment<br>  }<br>`;<br><br>function GroupLessonsContainer() {<br>  // subscription onNext callback udpates this reference.<br>  const [fragmentRef, setFragmentRef] = useState();<br>  // IMPORTANT: your config should be memoized.<br>  // Otherwise, useSubscription will re-render too frequently.<br>  // subsctiption configurations, that will be used later inside &quot;useCallback&quot; hook/<br>  const groupLessonConfig = useMemo(() =&gt; ({<br>    subscription: GroupLessonsSubscription,<br>    variables: {<br>      currentTime: DateTime.now(),<br>      endTime: DateTime.now().plus({ days: 3 }),<br>    },<br>    // a callback that is executed when a subscription payload is received<br>    onNext: (res) =&gt; {<br>      // In res, we get the updated reference that, we can use in <br>      // GroupLessonsPage to read updated data from relay store.<br>      setFragmentRef(res); // here we will get the fragment Reference<br>    },<br>    // a callback that is executed when the subscription errors.<br>    onError: (err: any) =&gt; {},<br>    // a callback that is executed when the server ends the subscription<br>    onCompleted: () =&gt; {},<br>  }), []);<br><br>  // executing the subscription.<br>  useSubscription(groupLessonConfig);<br><br>  return fragmentRef<br>    ? &lt;GroupLessonsPage fragmentRef={fragmentRef} /&gt;<br>    : &lt;h2&gt;loading...&lt;/h2&gt;<br>}<br><br><br>function GroupLessonsPage({ fragmentRef }) {<br>  // reading fragment data<br>  const storeData = useFragment(fragment, fragmentRef);<br><br>  const lessons = storeData?.appt_group_connection?.edges;<br><br>  return (<br>    lessons.map((item) =&gt; {<br>      return (&lt;p&gt;lesson minutes: {item.node.minutes}&lt;/p&gt;<br>      &lt;p&gt;total students in lesson: {item.node.students}&lt;/p&gt;);<br>    })<br>  )<br>}</pre><p>You have noticed, we spread the <strong>fragment</strong> inside <strong>subscription</strong> that’s because, we always wanted to read data from fragments as we’re using here the relay best practices. On the other hand, if we don’t spread fragment inside subscription and instead, write the fields directly, then in the <strong>onNext callback, </strong>instead of fragment reference, we get the direct data which we can even directly use without doing anything extra steps.</p><p>Hope all make sense if not, drop me a message on <a href="https://www.linkedin.com/in/syed-muhammad-ahmad-388006278/">Linkedin</a> OR <a href="https://www.buymeacoffee.com/syedmahmad">Buy me a cup of coffee</a></p><p>If you find this information valuable, please give it a thumbs up and consider following me for more updates.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=76489b6ebea0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Relay (modern) Simplified]]></title>
            <link>https://medium.com/@syedmahmad/react-relay-modern-simplified-956f33739f0?source=rss-83a494cbe898------2</link>
            <guid isPermaLink="false">https://medium.com/p/956f33739f0</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[relay]]></category>
            <category><![CDATA[reactrelaysimplified]]></category>
            <category><![CDATA[relay-modern]]></category>
            <category><![CDATA[relay-hook]]></category>
            <dc:creator><![CDATA[Syed M Ahmad]]></dc:creator>
            <pubDate>Tue, 12 Sep 2023 07:40:51 GMT</pubDate>
            <atom:updated>2023-09-13T11:49:50.278Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7pt1Uupl4vQ-JYlENYZrnw.png" /></figure><p>Relay is critical infrastructure in Facebook, there are tens of thousands of components using it. It is <strong>Not Just for Big Apps </strong>but If you’re the sort of team that believes in using Flow or TypeScript to move error detection to dev-time, then Relay is likely a good fit for you.</p><p>It is designed for high performance at any scale. Relay keeps management of data-fetching easy, whether your app has tens, hundreds, or thousands of components. Unfortunately, the people at Facebook haven’t put much effort into documenting Relay properly. The examples in the documentation are broken at places and the documentation itself is barely complete.</p><p>Here is my attempt to <strong>simplify relay modern</strong>. The majority of the content presented here draws from my experiences with Relay in both professional work settings and personal projects.</p><h4>Benefits of relay</h4><p>Relay knows that we all make mistakes. that’s why it sets up for success with strick conventions.</p><ul><li>Relay minimize dev error.</li><li>Maximize performance.</li><li>For both above points, relay use relay compiler.</li></ul><h4>Relay Compiler</h4><p>It is composer of graphQL fragments. Just like components are composed into a tree. It is based on same react data modal. Relay data fragments are composed into a query. this will reduce round trip of the server.</p><p><strong>Relay Compiler Benefits</strong>:</p><ul><li>Auto type generation</li><li>default is flow types but you can integrate typescript</li><li>Types are great because it prevents bugs.</li><li><strong>Transform:</strong> Optimize queries by removing redundancies. which reduces query payload size. which is great for performance.</li><li><strong>Persisted Queries:</strong> Enable with persist-output-flag. when this is enabled, it converted your graphQL operations into <strong>md5</strong> hashes. <strong>md5</strong> hashes make our string shorter, which reduces query payload size even more.</li><li><strong>Whitelist Queries:</strong> this will improve security.</li></ul><h4>How we move forward</h4><p>We’ll create small and complete examples for each feature defined above with <strong>relay modern using hooks</strong>. So, It will much more easier for everyone, no, matter how much experience do you have in react relay.</p><h4>Main features to cover</h4><ul><li><a href="https://medium.com/@syedmahmad/relay-fragments-simplified-7a4f321981cf">Fragments</a></li><li><a href="https://medium.com/@syedmahmad/relay-fetch-data-via-queries-simplified-91fb5a6f14df">Queries</a></li><li><a href="https://medium.com/@syedmahmad/relay-subscriptions-with-fragments-simplified-76489b6ebea0">Mutations</a></li><li><a href="https://medium.com/@syedmahmad/relay-subscriptions-with-fragments-simplified-76489b6ebea0">Subscription</a></li><li><a href="https://medium.com/@syedmahmad/relay-time-base-caching-on-individual-or-specific-queries-a4c9debbfac9">Cache Specific Queries</a></li><li><a href="https://medium.com/@syedmahmad/react-relay-resolvers-ef3798dc57a0">Resolvers</a></li></ul><h4>Conclusion</h4><p>The aim of this blog is to streamline Relay for you, offering comprehensive examples that eliminate the frustration of navigating incomplete or flawed code samples mentioned in documentation. Relay is great as it is baked with graphQL best practices. You can use Relay out of the box with Create React App and Next.js.</p><p>Hope all make sense if not, drop me a message on <a href="https://www.linkedin.com/in/syed-muhammad-ahmad-388006278/">Linkedin</a> OR <a href="https://www.buymeacoffee.com/syedmahmad">Buy me a cup of coffee</a></p><p>If you find this information valuable, please give it a thumbs up and consider following me for more updates.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=956f33739f0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Relay fetch data via Queries (Simplified)]]></title>
            <link>https://medium.com/@syedmahmad/relay-fetch-data-via-queries-simplified-91fb5a6f14df?source=rss-83a494cbe898------2</link>
            <guid isPermaLink="false">https://medium.com/p/91fb5a6f14df</guid>
            <category><![CDATA[relay-modern]]></category>
            <category><![CDATA[relay]]></category>
            <category><![CDATA[relay-data-fetching]]></category>
            <category><![CDATA[useloaderdata]]></category>
            <category><![CDATA[react-hook]]></category>
            <dc:creator><![CDATA[Syed M Ahmad]]></dc:creator>
            <pubDate>Mon, 11 Sep 2023 16:31:08 GMT</pubDate>
            <atom:updated>2023-09-12T07:42:57.677Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WR2v3F38_-BOnD2BIbeHPg.jpeg" /></figure><p>This article is a segment of my “<a href="https://medium.com/@syedmahmad/956f33739f0">Simplified React Relay (modern)</a>” series. If you’re interested in understanding what React Relay is and how to seamlessly implement it in your applications, you’ve come to the right place. I’ve endeavored to encompass all the subjects with straightforward examples to ensure accessibility for everyone.</p><h3>Introduction</h3><p>In Relay Modern there are 4 hooks available to fetch data.</p><ul><li><a href="https://relay.dev/docs/api-reference/use-lazy-load-query/">useLazyLoadQuery</a></li><li><a href="https://relay.dev/docs/api-reference/use-preloaded-query/">usePreloadedQuery</a></li><li><a href="https://relay.dev/docs/api-reference/use-query-loader/">useQueryLoader</a></li><li><a href="https://relay.dev/docs/api-reference/load-query/">loadQuery</a></li></ul><h4>useLazyLoadQuery</h4><p>It fetch the query during render phase (react) and it may suspend while the network request on the fly. It will throw errors if network error occur which can be caught and rendered with Error Boundaries. The component automatically subscribed to updates to the query data: if the data for this query is updated anywhere in the app.</p><p>Although, the lazyLoadQuery is good but it is not recommended and we should have to use usePreloadedQuery as it fetch data earlier while not blocking rendering.</p><pre>const React = require(&#39;React&#39;);<br><br>const {graphql, useLazyLoadQuery} = require(&#39;react-relay&#39;);<br><br>// this App component should be wrapped inside ErrorBoundary.<br>function App() {<br>  const data = useLazyLoadQuery(<br>    graphql`<br>      query AppQuery($id: ID!) {<br>        user(id: $id) {<br>          name<br>        }<br>      }<br>    `,<br>    {id: 4},<br>    {fetchPolicy: &#39;store-or-network&#39;},<br>  );<br><br> return &lt;Suspense fallback={&lt;h2&gt;..loading&lt;/h2&gt;}&gt;&lt;h1&gt;{data.user?.name}&lt;/h1&gt;&lt;/Suspense&gt;;<br>}</pre><p>The other three hooks function cohesively, and I won’t delve into their detailed descriptions here, which can be found in the official documentation. My goal is to provide a simplified working example to make them accessible to everyone.</p><p>In my opinion, there are two primary use cases for data retrieval. I’ve attempted to provide concise examples that can assist you in establishing a well-structured approach.</p><ul><li><a href="https://medium.com/@syedmahmad/relay-fetch-queries-on-page-load-simplified-4ead5e9d7c5c">Relay fetch queries on page load (Simplified)</a></li><li><a href="https://medium.com/@syedmahmad/relay-fetch-queries-on-user-interactions-simplified-4f2f8a760fab">Relay fetch queries on user interactions (Simplified)</a></li></ul><p>Hope all make sense if not, drop me a message on <a href="https://www.linkedin.com/in/syed-muhammad-ahmad-388006278/">Linkedin</a> OR <a href="https://www.buymeacoffee.com/syedmahmad">Buy me a cup of coffee</a></p><p>If you find this information valuable, please give it a thumbs up and consider following me for more updates.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=91fb5a6f14df" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Relay fetch queries on user interactions (Simplified)]]></title>
            <link>https://medium.com/@syedmahmad/relay-fetch-queries-on-user-interactions-simplified-4f2f8a760fab?source=rss-83a494cbe898------2</link>
            <guid isPermaLink="false">https://medium.com/p/4f2f8a760fab</guid>
            <category><![CDATA[relay-hooks-to-fetch-data]]></category>
            <category><![CDATA[relay-modern]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[relay-best-practices]]></category>
            <category><![CDATA[relay]]></category>
            <dc:creator><![CDATA[Syed M Ahmad]]></dc:creator>
            <pubDate>Mon, 11 Sep 2023 16:22:46 GMT</pubDate>
            <atom:updated>2023-09-12T07:46:38.392Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*YY0bo4HYrc2I9d6nh7bNeA.jpeg" /></figure><p>This article is a segment of my “<a href="https://medium.com/@syedmahmad/956f33739f0">Simplified React Relay (modern)</a>” series. If you’re interested in understanding what React Relay is and how to seamlessly implement it in your applications, you’ve come to the right place. I’ve endeavored to encompass all the subjects with straightforward examples to ensure accessibility for everyone.</p><h3>Introduction</h3><p>In this article, we aim to explain how you can retrieve query data based on user interactions. In Relay Modern, there are three hooks that can be combined to achieve this objective.</p><h4>loadQuery, useQueryLoader, usePreloadedQuery</h4><ul><li>The combination of <strong>useQueryLoader</strong> and <strong>usePreloadedQuery</strong> enables data fetching in accordance with the <strong>render-as-you-fetch pattern</strong>. These two hooks come highly recommended over <strong>useLazyLoadQuery</strong> due to their speed and non-disruptive rendering of other components.</li><li>Directly invoking <strong>loadQuery</strong> is discouraged since its return value is unstable and prone to change. Instead, it is advisable to utilize <strong>useQueryLoader</strong>, which also provides access to <strong>loadQuery</strong>, ensuring a more stable and reliable way to fetch data. but if you really wanted to use it then, take care of the dispose on component unmount.</li></ul><p>Let’s take an example like, how you can use them together.</p><pre>const HomeQuery = graphql`<br>  query AppQuery($id: ID!) {<br>    user(id: $id) {<br>      name<br>    }<br>  }<br>`;<br><br>function HomePage() {<br>  const [queryReference, loadQuery] = useQueryLoader(HomeQuery);<br><br>  if (queryReference == null) {<br>    return (<br>      &lt;Button onClick={() =&gt; loadQuery({})}&gt; Click to reveal the name &lt;/Button&gt;<br>    );<br>  }<br><br>  return (<br>    &lt;React.Suspense fallback=&quot;Loading&quot;&gt;<br>      &lt;NameDisplay queryReference={queryReference} /&gt;<br>    &lt;/React.Suspense&gt;<br>  );<br>}<br><br>function NameDisplay({ queryReference }) {<br>  const data = usePreloadedQuery(AppQuery, queryReference);<br><br>  return &lt;h1&gt;{data.user?.name}&lt;/h1&gt;;<br>}</pre><p>This was the simplest example but you may link it to complex examples as well.</p><p>Hope all make sense if not, drop me a message on <a href="https://www.linkedin.com/in/syed-muhammad-ahmad-388006278/">Linkedin</a> OR <a href="https://www.buymeacoffee.com/syedmahmad">Buy me a cup of coffee</a></p><p>If you find this information valuable, please give it a thumbs up and consider following me for more updates.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4f2f8a760fab" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Relay fetch queries on page load (Simplified)]]></title>
            <link>https://medium.com/@syedmahmad/relay-fetch-queries-on-page-load-simplified-4ead5e9d7c5c?source=rss-83a494cbe898------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ead5e9d7c5c</guid>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[relay]]></category>
            <category><![CDATA[relay-modern]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[relay-queries]]></category>
            <dc:creator><![CDATA[Syed M Ahmad]]></dc:creator>
            <pubDate>Mon, 11 Sep 2023 15:45:17 GMT</pubDate>
            <atom:updated>2023-09-12T07:43:56.155Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fGaAOO9i6Od5GQR-2ESG5Q.jpeg" /></figure><p>This article is a segment of my “<a href="https://medium.com/@syedmahmad/956f33739f0">Simplified React Relay (modern)</a>” series. If you’re interested in understanding what React Relay is and how to seamlessly implement it in your applications, you’ve come to the right place. I’ve endeavored to encompass all the subjects with straightforward examples to ensure accessibility for everyone.</p><h3>Introduction</h3><p>Next JS makes it easy to fetch queries on page load via <a href="https://nextjs.org/docs/pages/api-reference/functions/get-initial-props">getInitialProps</a> OR <a href="https://nextjs.org/docs/pages/building-your-application/data-fetching/get-server-side-props">getserversideProps</a> methods but in React it was hard to do so.</p><p>Fortunately, <a href="https://reactrouter.com/en/main/route/loader">react-router v6</a> helps to achieve the same functionality.</p><p>In the relay modern, we can use <strong>lazyLoad</strong> hook or <strong>preloaded</strong> hook to <strong>load the queries via Network. </strong>In this example, we use <strong>relay best practices</strong>, which means, we’re using <strong>preLoaded query</strong> here.</p><p>Here are the steps to follow.</p><p>1- fetching data in home route with the help of <strong>loader</strong>.</p><pre>const HomeQuery = graphql`<br>  query HomeQuery($id: ID!) {<br>    user(id: $id) {<br>      name<br>    }<br>  }<br>`;<br><br>const {graphql, loadQuery} = require(&#39;react-relay&#39;);<br>createBrowserRouter([<br>    {<br>      path: &quot;home&quot;,<br>      element: &lt;Suspense fallback={loading...}&gt;&lt;HomePage /&gt;&lt;/Suspense&gt;,<br>      loader: async () =&gt; loadQuery(<br>          AppEnvironment, // relay environment<br>          HomeQuery,      // query to load<br>          { id: &#39;4&#39; },    // variables, if any<br>          { fetchPolicy: &#39;store-or-network&#39; }, // fetch policy<br>      ),<br>      errorElement: &lt;PageLevelError /&gt; // handle error if any <br>      children: [...]<br>    }<br>  ]);<br></pre><p>2- In the home page, get the data returned via <strong>loadQuery</strong> like following.</p><pre>...<br>import { useLoaderData } from &#39;react-router-dom&#39;;<br><br>const Home = () =&gt; {<br>  // TQuery is a type which you can pick from __generated__ file<br>  const queryReference = useLoaderData();<br><br>  const data = usePreloadedQuery(HomeQuery, queryReference);<br><br>  useEffect(() =&gt; {<br>    // need to dispose on unmount.<br>    () =&gt; queryReference.dispose()l<br>  }, [])<br><br>  return &lt;h1&gt;{data.user?.name}&lt;/h1&gt;;<br>};<br><br>export default Home;</pre><p>The <strong>loadQuery</strong> callback will throw an error if it is called during React’s render phase but fortunately with the above setup, you’re able to catch the error in <strong>errorElement </strong>and inside the <strong>&lt;PageLevelError /&gt; </strong>we can pick the error message like following.</p><pre>import { useRouteError } from &#39;react-router-dom&#39;;<br><br>export const PageLevelError = () =&gt; {<br>  const error = useRouteError();<br><br>  useEffect(() =&gt; {<br>    if (error) {<br>       log(error);<br>    }<br>  }, [error]);<br><br>  return (<br>   ....<br>  );<br>};</pre><h4>Conclusion</h4><p>Hope all these make sense and now you are able to create many more routes easily. This is called “<strong>render-as-you-fetch</strong>” pattern. This pattern is encouraged over useLazyLoadQuery() as it can allow fetching data earlier while not blocking rendering.</p><p>Hope all make sense if not, drop me a message on <a href="https://www.linkedin.com/in/syed-muhammad-ahmad-388006278/">Linkedin</a> OR <a href="https://www.buymeacoffee.com/syedmahmad">Buy me a cup of coffee</a></p><p>If you find this information valuable, please give it a thumbs up and consider following me for more updates.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ead5e9d7c5c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Relay Fragments (simplified)]]></title>
            <link>https://medium.com/@syedmahmad/relay-fragments-simplified-7a4f321981cf?source=rss-83a494cbe898------2</link>
            <guid isPermaLink="false">https://medium.com/p/7a4f321981cf</guid>
            <category><![CDATA[fragments]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[relay]]></category>
            <category><![CDATA[relay-modern]]></category>
            <category><![CDATA[nextjs]]></category>
            <dc:creator><![CDATA[Syed M Ahmad]]></dc:creator>
            <pubDate>Fri, 08 Sep 2023 13:54:33 GMT</pubDate>
            <atom:updated>2023-09-13T09:13:36.951Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*2H15IUntVco6tqRb_-LLwQ.jpeg" /></figure><p>This article is a segment of my “<a href="https://medium.com/@syedmahmad/956f33739f0">Simplified React Relay (modern)</a>” series. If you’re interested in understanding what React Relay is and how to seamlessly implement it in your applications, you’ve come to the right place. I’ve endeavored to encompass all the subjects with straightforward examples to ensure accessibility for everyone.</p><h4>Introduction</h4><p>Fragments are reusable units in GraphQL. We compose these units (set of data) inside <strong>query</strong> to load required data from Network/Backend. On successful response of the query, <strong>relay store</strong> hold that data. Components use fragments to declare their data dependencies, and read data from the Relay store by calling <a href="https://relay.dev/docs/api-reference/use-fragment/">useFragment</a> hook.</p><blockquote><strong>NOTE</strong>: Fragments cannot be fetched by themselves; instead, they must ultimately be included in a parent query. The Relay compiler will then ensure that the data dependencies declared in such fragments are fetched as part of that parent query.</blockquote><h4>useFragment</h4><p>This hook <strong>read the data from relay store</strong> and display it on the component. so, it means, this hook, does not fetch data from network, it <strong>just contact with relay store</strong> and read data form it if available else empty data.</p><ul><li>We can use usefragment multiple time in the same component if need data form multiple fragments in the same component.</li></ul><h4>useFragment Working Mechanism</h4><p>It takes two parameters: a <strong>fragment literal</strong> and a <strong>fragment reference</strong>. A fragment reference specifies <em>which</em> entity data to read from <strong>relay store</strong>.</p><p>Here is the simple example.</p><pre>// define fragment<br>const fragment = graphql`<br>  fragment ArtistHeader_artist on Artist {<br>        href<br>        bio<br>        image {<br>          url<br>        }<br>      }<br>`;<br><br>// define query and spread your fragment name inside.<br>// You can add multiple fragments inside a single query<br> const ArtistQuery = graphql`<br>   query ArtistQuery {<br>      ...ArtistHeader_artist<br>    }<br>  `;<br><br><br>function FetchArtistData() {<br>  const [queryReference, loadQuery] = useQueryLoader(ArtistQuery);<br><br>  useEffect(() =&gt; {<br>    loadQuery({}); // this will load the data from network/backend<br>  }, []);<br><br>  return &lt;Suspense fallback=&quot;Loading...&quot;&gt;<br>    {queryReference != null<br>      ? &lt;LoadArtistDataReferenceFromStore queryReference={queryReference}/&gt;<br>      : null<br>    }<br>   &lt;/Suspense&gt;<br>}<br><br><br>function LoadArtistDataReferenceFromStore({ queryReference }) {<br>  const fragmentRef = usePreloadedQuery(ArtistQuery, queryReference);<br><br>  return &lt;ReadArtistData fragmentRef={fragmentRef}/&gt;<br>}<br><br>function ReadArtistDataFromStore({ queryReference }) {<br>  const {href, image, bio} = useFragment(fragment, fragmentRef);<br><br>  const imageUrl = image &amp;&amp; image.url;<br><br>  return (<br>    &lt;Card&gt;<br>      &lt;Link href={href}&gt;<br>        &lt;Image imageUrl={imageUrl} /&gt;<br>        &lt;Bio&gt;{bio}&lt;/Bio&gt;<br>      &lt;/Link&gt;<br>    &lt;/Card&gt;<br>  );<br>}</pre><h4>Conclusion</h4><p>I have used the preloaded Query here along with queryLoader but you may go with <strong>useLazyLoad</strong> query too which is relative easier to setup. I just wanted to give you context about preloaded queries too as mentioned in the docs, its setup is little hard for developers.</p><p>Hope all make sense if not, drop me a message on <a href="https://www.linkedin.com/in/syed-muhammad-ahmad-388006278/">Linkedin</a> OR <a href="https://www.buymeacoffee.com/syedmahmad">Buy me a cup of coffee</a></p><p>If you find this information valuable, please give it a thumbs up and consider following me for more updates.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7a4f321981cf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Relay Resolvers (Simplified)]]></title>
            <link>https://medium.com/@syedmahmad/react-relay-resolvers-ef3798dc57a0?source=rss-83a494cbe898------2</link>
            <guid isPermaLink="false">https://medium.com/p/ef3798dc57a0</guid>
            <category><![CDATA[resolver]]></category>
            <category><![CDATA[resolver-problemas]]></category>
            <category><![CDATA[relay-modern]]></category>
            <category><![CDATA[graphql-resolver]]></category>
            <category><![CDATA[reactjs]]></category>
            <dc:creator><![CDATA[Syed M Ahmad]]></dc:creator>
            <pubDate>Wed, 06 Sep 2023 12:52:51 GMT</pubDate>
            <atom:updated>2023-09-12T12:18:21.026Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*1vqmXSHmQ--5QQ8jloomlg.jpeg" /></figure><p>This article is a segment of my “<a href="https://medium.com/@syedmahmad/956f33739f0">Simplified React Relay (modern)</a>” series. If you’re interested in understanding what React Relay is and how to seamlessly implement it in your applications, you’ve come to the right place. I’ve endeavored to encompass all the subjects with straightforward examples to ensure accessibility for everyone.</p><h4>Introduction</h4><p>Relay stands as a potent tool for building and sustaining data-driven React applications. In this article, we will delve into the world of Relay resolvers, a feature that empowers us to introduce client-only custom fields into Relay’s GraphQL graph. While we assume prior familiarity with React, Relay, and GraphQL, we have compiled some valuable resources for those who may need to brush up on these topics.</p><ul><li><strong>Relay docs</strong>: <a href="https://relay.dev/docs/en/introduction-to-relay">https://relay.dev/docs/en/introduction-to-relay</a></li><li><strong>Relay community resources:</strong> <a href="https://relay.dev/docs/en/community-learning-resources">https://relay.dev/docs/en/community-learning-resources</a></li><li><strong>Relay Resolvers: </strong><a href="https://relay.dev/docs/guides/relay-resolvers/">https://relay.dev/docs/guides/relay-resolvers/</a></li></ul><blockquote>NOTE: We would like to draw attention to some crucial points that are not adequately covered in the <a href="https://relay.dev/docs/guides/relay-resolvers/">official documentation</a>. Specifically, we want to highlight the experimental nature of resolvers. While this feature shows great promise, its maturity level is uncertain. Nevertheless, we are committed to assisting those who are eager to explore and utilize this remarkable feature.</blockquote><h4>Let’s start</h4><p>Within the resolver, we define a new data type, and if there are alterations to the underlying base data, our derived data, which we have specified within the resolver, will automatically adjust accordingly.</p><p>Here are the steps.</p><p>1- In the `<em>relay.config.js</em>` enable <em>resolver</em> feature like following.</p><pre>...<br>featureFlags: {<br>    enable_relay_resolver_transform: true<br>  },<br>...</pre><p>2- in the relay `environment` OR `App.tsx` file, enable resolver again form relay-runtime like follwoing.</p><pre>import { RelayFeatureFlags } from &#39;relay-runtime&#39;;<br>RelayFeatureFlags.ENABLE_RELAY_RESOLVERS = true;<br>...</pre><p>3- Write your resolver by remember the following important parts.</p><ul><li>Should write correct <a href="https://relay.dev/docs/guides/relay-resolvers/#docblock-fields"><strong>Docblock Fields</strong></a> as relay compiler needs this in correct way.</li><li><a href="https://relay.dev/docs/guides/relay-resolvers/#relay-resolver-signature">Relay Resolver Signature</a> should be correct otherwise your resolver will not auto execute. Yes, you don’t even need to execute your resolver, if you have proper configuration, relay will auto execute your resolver and create new derived field. ****</li><li>Properly pick your database table name from your scheme where you wanted to derive a new state. Here is the short example code for future references. We are deriving new state (<strong>firstName</strong>) from the <strong>resource title (FullName)</strong>.</li></ul><pre>import { graphql } from &#39;babel-plugin-relay/macro&#39;;<br>import { readFragment } from &#39;relay-runtime/lib/store/ResolverFragments&#39;;<br>import type { firstNameResolver$key } from &#39;./__generated__/firstNameResolver.graphql&#39;;<br><br>/**<br> * @RelayResolver<br> * @onType resources<br> * @fieldName firstName<br> * @rootFragment firstNameResolver<br> */<br><br>export function firstName(ResourcesKey: firstNameResolver$key) {<br>  const data = readFragment(graphql`<br>  fragment firstNameResolver on resources <br>    {<br>      title<br>    }<br>  `, ResourcesKey);<br>  return data?.title.split(&#39; &#39;)[0];<br>}</pre><p><strong>4- Most important step</strong> is to use that new firstName field in your fragment or anywhere you wanted to use. <strong>If you don’t do this step</strong>, you will see no change (nothing) and your resolver never execute as the rule of thumb is:</p><ul><li>Your resolver will auto execute once the new field (i-e <strong>firstName</strong>) you derived from parent field (i-e <strong>title</strong>) is being used in some of your component</li><li>So, here is, we are using this new derived filed.</li></ul><pre>const data = useFragment(graphql`<br>    fragment Welcome_query on query_root {<br>      resources_connection {<br>        edges { <br>          node { <br>            title<br>            firstName<br>          } <br>        } <br>      }<br>    }<br>  `, fragmentRef);<br>  const teacherData = data.resources_connection.edges;<br>  console.log(teacherData[0].node.firstName)</pre><p>5- Finally, In the relay stere, you’re able to see <strong>resolvers derived data</strong> like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NGgjfNfb5aUjpaf_avNN2Q.png" /></figure><h4>Concluion</h4><p>In this article, I tried to explain, how to <strong>derive</strong> a new client side filed from <strong>parent</strong> fields via relay resolvers and if there is any change in parent field, new derived filed will auto update.</p><p>Hope all make sense if not, drop me a message on <a href="https://www.linkedin.com/in/syed-muhammad-ahmad-388006278/">Linkedin</a> OR <a href="https://www.buymeacoffee.com/syedmahmad">Buy me a cup of coffee</a></p><p>If you find this information valuable, please give it a thumbs up and consider following me for more updates.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ef3798dc57a0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Achieving Time-Based Caching for Specific Queries with Relay Modern Network Layer]]></title>
            <link>https://medium.com/@syedmahmad/relay-time-base-caching-on-individual-or-specific-queries-a4c9debbfac9?source=rss-83a494cbe898------2</link>
            <guid isPermaLink="false">https://medium.com/p/a4c9debbfac9</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[relay-network]]></category>
            <category><![CDATA[caching]]></category>
            <category><![CDATA[relay-modern]]></category>
            <dc:creator><![CDATA[Syed M Ahmad]]></dc:creator>
            <pubDate>Mon, 04 Sep 2023 10:32:46 GMT</pubDate>
            <atom:updated>2023-09-12T12:04:27.000Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JFbvRe1lJH_WZGSBPoFdVQ.jpeg" /></figure><p>This article is a segment of my “<a href="https://medium.com/@syedmahmad/956f33739f0">Simplified React Relay (modern)</a>” series. If you’re interested in understanding what React Relay is and how to seamlessly implement it in your applications, you’ve come to the right place. I’ve endeavored to encompass all the subjects with straightforward examples to ensure accessibility for everyone.</p><h3>Introduction</h3><p>Relay is a powerful tool for creating and maintaining <strong>data-driven</strong> React applications. In this article, we’ll explore a useful practice: implementing time-based caching for specific queries in Relay Network Layer. We assume that you’re already familiar with <strong>React, Relay, and GraphQL</strong>. If you need to brush up on these technologies, there are plenty of resources available:</p><ul><li><strong>Relay docs</strong>: <a href="https://relay.dev/docs/en/introduction-to-relay">https://relay.dev/docs/en/introduction-to-relay</a></li><li><strong>Relay community resources:</strong> <a href="https://relay.dev/docs/en/community-learning-resources">https://relay.dev/docs/en/community-learning-resources</a></li></ul><h3>UseCase</h3><p>By default, relay modern cache queries data but this goes for all queries, let’s say, if you wanted to cache some queries not all? What if, you wanted to cache a specific query for only 10 mins etc?</p><p>Well, I came across the same situation and here, I am going to share, how I achieved this.</p><p>I found multiple examples over the internet but all seems outdated. Even In the <a href="https://relay.dev/docs/v9.1.0/network-layer/">official docs</a> (deprecated), they are talking about caching which we can apply in Network layer (globally for all queries).</p><h3>Custom Implementation</h3><p>There are 2 main steps involve</p><ul><li>Update your network layer. Before API call we’ll check if query is present in cache, <strong>render form cache</strong> else fetch from network and set it in cache with <strong>custom expiry time.</strong></li><li>Update the fetchPolicy in your query to control how often the query is executed.</li></ul><p>But moving forward, Need to understand following concepts first.</p><ul><li><strong>fetch policies in relay</strong>: <a href="https://relay.dev/docs/guided-tour/reusing-cached-data/fetch-policies/">https://relay.dev/docs/guided-tour/reusing-cached-data/fetch-policies/</a></li><li><strong>cacheConfig in relay:</strong> <a href="https://relay.dev/docs/api-reference/types/CacheConfig/">https://relay.dev/docs/api-reference/types/CacheConfig/</a></li><li><strong>Network Layer </strong>fetchQuery : <a href="https://relay.dev/docs/guides/network-layer/">https://relay.dev/docs/guides/network-layer/</a></li><li><strong>useLazyLoadQuery</strong> Arguments: <a href="https://relay.dev/docs/api-reference/use-lazy-load-query/">https://relay.dev/docs/api-reference/use-lazy-load-query/</a></li></ul><h3>Let’s start with coding example</h3><p>In the relay network layer mostly all developer’s define fetchQuery callback and pass it to relay environment (singleton instance) like following.</p><pre>// creating a singleton instance of Relay Environment<br>const AppEnvironment = new Environment({<br>  network: Network.create(fetchQuery),<br>  ...<br>});<br><br>// this fetchQuery callback takes some arguments like following.<br>async function fetchQuery(params: RequestParameters,variables: Variables, <br>cacheConfig: CacheConfig) {<br>    ......<br> }</pre><blockquote><strong>Question is</strong>, when/how this fetchQuery works! Does, it execute, every-time component render or re-render?</blockquote><p>Well! It depends on your <a href="https://relay.dev/docs/guided-tour/reusing-cached-data/fetch-policies/"><em>fetchPolicy</em></a>. By default, It executes queryonly once, due to default policy store-or-network First time, it fetches the query data form network and cache it in relay store. On re-rendering, it immediately render the data from store and do not execute query again. It means, relay have really good mechanism of caching.</p><p>Later! if cached data is stale or (query, mutation) updated by developer, relay garbageCollector come into the action and clean the previous cached data.</p><h3>How to override default behaviour</h3><p>We can override relay default behaviour by updating fetchPolicy which will allow network layer fetchQuery to not execute only once</p><p>if the fetchQuery executes on every re-render then we need handle network requests (stop) by writing small code which will not always send API call (network request) and check data from cache first if data is present, it returns that data and if not, fetch data from network and cache it with the expiry time. Let’s take an example.</p><pre>const data = useLazyLoadQuery&lt;ResourceDataQuery&gt;(<br> graphql`<br>     query ResourceDataQuery ($id: Int!){<br>         resources_connection(where: {pk: {_eq: $id}}) {<br>         edges {<br>             node {<br>                 title<br>                 }<br>             }<br>         }<br>     }<br> `,<br>    { id: 2 },<br>    {<br>      fetchPolicy: &#39;store-and-network&#39;,<br>      networkCacheConfig: {<br>        force: false<br>      }<br>    }<br>  );</pre><p>By updating this policy, our Network layer fetchQuery callback will no longer executes only once. It executes every-time when user revisit the page or component. Here, we can update fetchQuery callback in network layer and can implement our custom <em>cacheConfig</em> via <em>QueryResponseCache</em> like following.</p><pre>// Network Layer Code...<br>import {<br>  RequestParameters,<br>  Variables,<br>  Environment,<br>  Network,<br>  QueryResponseCache,<br>  LogEvent,<br>  CacheConfig,<br>  Store,<br>  Observable,<br>  RecordSource,<br>} from &#39;relay-runtime&#39;;<br><br>// Helper functions starts...<br>// these functions are used to set expiry time of queries via QueryResponseCache<br>const caches:any = {};<br>// relay helper which allow us to create query cache based on time defined and size.<br>const getQueryResponseCache = (ttl: number) =&gt; {<br>  if (!caches[ttl]) {<br>    caches[ttl] = new QueryResponseCache({ size: 100, ttl });<br>  }<br>  return caches[ttl];<br>};<br>// you can add more queries name here if you wanted to apply time base caching on more querries<br>const operationNameToTTL:any = {<br>    &quot;ResourceDataQuery&quot;: 60 * 1000, // 60 seconds, to resolve preloaded results,<br>};<br>  // helper to apply cache expiry time to specific queries defined in operationNameToTTL.<br>const getTTLFromOperationName = (operationName: string) =&gt; operationNameToTTL[operationName] || 900000; // default 15 mins<br><br>// helper to check if oepration type is query.<br>const isQuery = (request: any) =&gt; request.operationKind === &#39;query&#39;;<br><br>// helper to allow if need to send network call by force instead of reusing from cache.<br>const forceFetch = (cacheConfig: CacheConfig) =&gt; !!(cacheConfig &amp;&amp; cacheConfig.force);<br>// Helper functions ends...<br><br><br><br>// Relay passes a &quot;params&quot;, &quot;variables&quot; and &quot;cacheConfig&quot; objects.<br>// Relay will also pass default cacheConfig value (force: true) in case of <br>// default fetchPolicy: &#39;store-or-network&#39;, we can override this behavious by updating <br>// fetch policy and updage cacheConfig (force: false)<br>// &quot;store-or-network&quot; it only executes once.<br>// &quot;store-and-network&quot; it only executes everytime on component render or re-render.<br>async function fetchQuery(<br>  params: RequestParameters,<br>  variables: Variables,<br>  cacheConfig: CacheConfig<br>) {<br>  const queryID = params.text!;<br>  let cache:any = null;<br>  // Main time base caching strategy starts...<br>  // In this example, we are just applying time base caching on ResourceDataQuery<br>  // we can add more queries here.<br>  // Instead of mentioning name here for each query, we can also add just one condition<br>  // if (!cacheConfig.force) but we cannot rely on this condition due to multiple reasons<br>  if (params.name === &#39;ResourceDataQuery&#39;) {<br>    // creating QueryResponseCache object with the default time of 60 seconds<br>    cache = getQueryResponseCache(getTTLFromOperationName(params.name));<br>    // reading from cache<br>    const fromCache = cache.get(queryID, variables);<br>    if (isQuery(params) &amp;&amp; fromCache !== null &amp;&amp; !forceFetch(cacheConfig)) {<br>      return fromCache;<br>    }<br>  }<br>  // Main time base caching strategy ends...<br><br>  // sending network request<br>  const BASE_API_URL = `${process.env.REACT_APP_BASE_API}`;<br>  let jsonResponse: any = {};<br>  try {<br>    const response = await fetch(BASE_API_URL, {<br>      method: &#39;POST&#39;,<br>      headers: {<br>        &#39;Content-Type&#39;: &#39;application/json&#39;,<br>        Authorization: `Bearer ${yourToken}`,<br>      },<br>      body: JSON.stringify({<br>        query: params.text,<br>        variables,<br>      }),<br>    });<br>    jsonResponse = await response.json();<br>    // setting the cashe in case of ResourceDataQuery only<br>    if (params.name === &#39;ResourceDataQuery&#39;) {<br>      cache.set(queryID, variables, jsonResponse);<br>    }<br>  } catch (err: any) {<br>    throw new Error(err?.message || &#39;Something went wrong.&#39;);<br>  }<br>  /**<br>   * In case of exceptions (for example, a missing required variable) in the &quot;errors&quot;<br>   * property of the response. If any exceptions occurred when processing the request,<br>   * throw an error to indicate to the developer what went wrong.<br>   * */<br>  if (Array.isArray(jsonResponse.errors)) {<br>    throw new Error(<br>      `Error fetching GraphQL query &#39;${<br>        params.name<br>      }&#39; with variables &#39;${JSON.stringify(variables)}&#39;: ${JSON.stringify(<br>        jsonResponse.errors,<br>      )}`,<br>    );<br>  }<br>  return jsonResponse;<br>}<br><br>// creating a singleton instance of Relay Environment<br>const AppEnvironment = new Environment({<br>  // registering the fetchRelay and fetchSubscribe callbacks in Network Layer.<br>  network: Network.create(fetchQuery),<br>  store: new Store(new RecordSource(), {<br>    /**<br>     * This property tells Relay to not immediately clear its cache when the user<br>     * navigates around the app. Relay will hold onto the specified number of<br>     * query results, allowing the user to return to recently visited pages<br>     * and reusing cached data if its available/fresh.<br>     */<br>    gcReleaseBufferSize: 10,<br>  }),<br>  // enabling relay logging for dev environment<br>  // log: relayTransactionLogger<br>});<br><br>export default AppEnvironment;</pre><h4>Concluion</h4><p>In this article, we’ve explored how to achieve time-based caching for specific queries in Relay Network Layer. By updating the fetchPolicy and implementing custom cache configurations, you can gain more control over when and how your queries are executed and cached. Feel free to adapt these techniques to your specific requirements.</p><p>Hope all make sense if not, drop me a message on <a href="https://www.linkedin.com/in/syed-muhammad-ahmad-388006278/">Linkedin</a> OR <a href="https://www.buymeacoffee.com/syedmahmad">Buy me a cup of coffee</a></p><p>If you find this information valuable, please give it a thumbs up and consider following me for more updates.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a4c9debbfac9" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>