<?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 Backspace Catalyst on Medium]]></title>
        <description><![CDATA[Stories by Backspace Catalyst on Medium]]></description>
        <link>https://medium.com/@backspacecatalyst?source=rss-eabc66769ef------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*nabGdGcq6NJU9RQfcVLOfg.jpeg</url>
            <title>Stories by Backspace Catalyst on Medium</title>
            <link>https://medium.com/@backspacecatalyst?source=rss-eabc66769ef------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 23:48:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@backspacecatalyst/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[Get updated data without refetch after CRUD — Utilise Apollo cache]]></title>
            <link>https://medium.com/nexl-engineering/get-updated-data-without-refetch-after-crud-utilise-apollo-cache-6b2829fb8a5c?source=rss-eabc66769ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/6b2829fb8a5c</guid>
            <category><![CDATA[apollo-cache]]></category>
            <category><![CDATA[apollo-client]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Backspace Catalyst]]></dc:creator>
            <pubDate>Mon, 14 Jul 2025 06:06:44 GMT</pubDate>
            <atom:updated>2025-09-22T00:42:45.013Z</atom:updated>
            <content:encoded><![CDATA[<h3>Get updated data without refetch after CRUD — Utilise Apollo cache</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8vUP8any4v8Jdp2joPAcRg.png" /></figure><p>Think about this situation, you have a to-do list app, in which you have a query to get all the tasks to show on the page, you have the mutations to, create, update and delete a particular task. Now the question is, what happens after users perform a mutation? How do we get the query to get tasks updated?</p><h3>The easiest solution — refetch queries</h3><pre>const { data } = useTasksQuery();<br>const [deleteTask] = useDeleteTaskMutation({<br>  refetchQueries: [&quot;Tasks&quot;],<br>});<br>const [updateTask] = useUpdateTaskMutation({<br>  refetchQueries: [&quot;Tasks&quot;],<br>});<br>const [createTask] = useCreateTaskMutation({<br>  refetchQueries: [&quot;Tasks&quot;],<br>});</pre><p>This makes sure the queries get refetched after your mutation.</p><h3>The problem of refetch queries</h3><p>But you are going to see a loading state during the refetch. It doesn’t feel nice for a user to see some latency after their update, and is the refetch really necessary? We updated the mutation so we should have all the latest data we need, why can’t we just use them?</p><h3>Not the nicest solution — managing your own data</h3><p>A solution is to maintain our own data, so creating a state to store the data and keep it updated ourselves.</p><pre>const [tasks, setTasks] = useState([]);<br><br>const { data } = useTasksQuery({<br>  onCompleted: (data) =&gt; {<br>    setTasks(data.tasks || []);<br>  },<br>});<br>const [deleteTask] = useDeleteTaskMutation({<br>  onCompleted: (data) =&gt; {<br>    setTasks(tasks.filter(each =&gt; each.id !== data.deleteTask.taskDeleted.id));<br>  },<br>});<br>const [updateTask] = useUpdateTaskMutation({<br>  onCompleted: (data) =&gt; {<br>    setTasks(...);<br>  },<br>});<br>const [createTask] = useCreateTaskMutation({<br>  onCompleted: (data) =&gt; {<br>    setTasks([data.createTask.taskCreated, ...tasks]);<br>  },<br>});</pre><p>This will work but it looks so clumsy! Isn’t the point of Apollo client to help us manage querying states? Why do we end up maintaining our own state…</p><h3>The solution — apollo cache</h3><p>It doesn’t need to be so complicated, Apollo client has its own cache layer that we can utilise to achieve get latest data without:</p><ul><li>doing another call to the query</li><li>maintaining our own state</li></ul><h4>Prerequisite — Set up apollo cache</h4><p>It’s super simple to set up apollo cache, in where you set up your apollo client, add the cache set up there.</p><pre>import { InMemoryCache, ApolloClient } from &#39;@apollo/client&#39;;<br><br>const client = new ApolloClient({<br>  ...otherThings,<br>  cache: new InMemoryCache(options) // &lt;- this is what you have to do<br>});</pre><h4>Get latest data after update</h4><p>If you have your query/mutation look like this:</p><pre>query Tasks {<br>  tasks {<br>    id # &lt;- you must have id here<br>    title<br>    status<br>  }<br>}<br><br>mutation UpdateTask(...) {<br>  updateTask(...) {<br>    isSuccess<br>    taskUpdated { # &lt;- also the mutation needs to return the updated data<br>      id<br>      title<br>      status<br>    }<br>  }<br>}</pre><p>This following code should just work, the cache will update.</p><pre>const { data } = useTasksQuery();<br>const [updateTask] = useUpdateTaskMutation();</pre><p>The reason is, when you return the updated data from the mutation, Apollo just knows to find the stale data and update the fields updated, given you always fetch id of any object you fetch, that’s how apollow knows which fragment to update (by fragment type + id).</p><h4>get latest data after delete</h4><p>Update is easy but delete is less straight forward. How can you let Apollo know when a fragment should be remove in cache? The answer is you can’t and we have to do a little trick here.</p><p>We can use this isDeleted pattern to treat delete like an update. Then in the code, we just filter out the deleted tasks.</p><pre>query Tasks {<br>  tasks {<br>    id # &lt;- you must have id here<br>    title<br>    status<br>    isDeleted<br>  }<br>}<br><br>mutation DeleteTask(...) {<br>  deleteTask(...) {<br>    isSuccess<br>    taskDeleted { <br>      id<br>      isDeleted # &lt;- the mutation returns the task deleted with isDeleted field<br>    }<br>  }<br>}</pre><pre>const { data } = useTasksQuery();<br>const taskToShow = data.tasks.filter(task =&gt; !task.isDeleted); // &lt;- trick here<br>const [deleteTask] = useDeleteTaskMutation();</pre><h4>get latest data after create</h4><p>Create is the most complex one. We have to manually update the cache ourselves.</p><pre>mutation CreateTask(...) {<br>  createTask(...) {<br>    isSuccess<br>    taskCreated { # &lt;- we need to return all the fields we have in tasks query<br>      id<br>      title<br>      status<br>      isDeleted<br>    }<br>  }<br>}</pre><pre>const { data } = useTasksQuery();<br>const [createTask] = useCreateTaskMutation({<br>  update: (cache, { data }) =&gt; {<br>      const existingTasks = cache.readQuery&lt;TasksQuery&gt;({<br>        query: TasksDocument,<br>      });<br>      cache.writeQuery&lt;TasksQuery&gt;({<br>        query: TasksDocument,<br>        data: {<br>          tasks: {<br>            ...existingTasks,<br>            data.createTask.taskCreated,<br>          },<br>        },<br>      });<br>    },<br>});</pre><h4>get latest data after load more</h4><p>If you have a load more logic on your listing query, it’s similar to create action, you just need to manually update the cache using updateQuery on fetchMore function.</p><pre>query Tasks($page:Int, $perPage:Int) {<br>  tasks(page: $page, perPage: $perPage) {<br>    id<br>    # ...more fields<br>  }<br>}</pre><pre>const { data, fetchMore } = useTasksQuery();<br>const [page, setPage] = useState&lt;number&gt;(1);<br>const onClickFetchMoreTasks = () =&gt; {<br>  fetchMore({<br>    variables: {<br>      page,<br>      perPage: 5,<br>    },<br>    updateQuery: (prev, { fetchMoreResult }) =&gt; {<br>      if (!fetchMoreResult) return prev;<br>      const existingTasks = prev.tasks;<br>      const moreTasks = fetchMoreResult.tasks;<br>      return {<br>        tasks: [...existingTasks, ...moreTasks],<br>      };<br>    },<br>  });<br>};</pre><p>Ta-da, now without any new request and without extra state, we have our query data up to date!</p><p>Enjoy coding =)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b2829fb8a5c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/nexl-engineering/get-updated-data-without-refetch-after-crud-utilise-apollo-cache-6b2829fb8a5c">Get updated data without refetch after CRUD — Utilise Apollo cache</a> was originally published in <a href="https://medium.com/nexl-engineering">NEXL Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to fix cypress component test expect function conflict with Jest/React testing library expect]]></title>
            <link>https://medium.com/nexl-engineering/how-to-fix-cypress-component-test-expect-function-conflict-with-jest-react-testing-library-expect-87ca65ad3233?source=rss-eabc66769ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/87ca65ad3233</guid>
            <category><![CDATA[cypress-testing]]></category>
            <category><![CDATA[react-testing-library]]></category>
            <dc:creator><![CDATA[Backspace Catalyst]]></dc:creator>
            <pubDate>Thu, 26 Jun 2025 04:21:11 GMT</pubDate>
            <atom:updated>2025-06-26T05:07:45.369Z</atom:updated>
            <content:encoded><![CDATA[<h3>Context</h3><p>The stack we want to make co-exist</p><ul><li>Cypress component test for component-level tests</li><li>React testing library for component-level tests</li><li>Jest for function-level unit tests</li></ul><h3>The Problem</h3><p>We want to start using react testing library for component-level tests too and because we can’t migrate all cypress component tests to RTL all at once, we need them to co-exist for some time.</p><p>And the problem is the types of expect from Cypress conflicts with Jest’s expect function. So you will see typescript complain like this.</p><p>Testing library test:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*htKRpyU328iy9AG359QZpg.png" /></figure><p>Jest unit test:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JVFyIv_sCKXPljM8CmTiuQ.png" /></figure><p>And that’s because Typescript thought the expect is Cypress’s expect even though we are in a Jest test.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/998/1*U14CV2deIy5tvTih1QSIAA.png" /></figure><h3>Key Ideas to the problem</h3><ul><li>Testing library’s expect is from Jest</li><li>Cypress’s expect uses Chai assertions which is different from Jest’s expect , thus the typing conflicts</li><li>Each kind of test actually runs fine, the only issue is typescript complaining about the types</li><li>Typescript is complaining because both expect is added globally so it’s confused about which expect is which</li></ul><h3>The solution (or rather workaround)</h3><ul><li>TL;DR — to explicitly tell typescript which expect to use in test files</li></ul><p>Without complex Typescript configs to exclude cypress for jest tests and jest for cypress tests, the easiest way is to just import the expect for each jest tests. Also don’t any jest import globally like in setupJest.ts because that will break cypress tests.</p><p>In Jest unit test, add:</p><pre>import { expect } from “@jest/globals”;</pre><p>Now you can see the expect is Jest’s expect and you can do jest assertions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bpSaxuTLYKgxqq2zDGH19A.png" /></figure><p>But if you do the same with testing library test, you will still see the error that even though the expect is jest expect now, it doesn’t recognise the assertion.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZIlSMVAidh6Qaidtm9hiwA.png" /></figure><p>That’s because the assertion is not Jest’s native assertions but from jest-dom by testing library. So we should import jest-dom in the test to fix this.</p><pre>import { expect } from &quot;@jest/globals&quot;;<br>import &quot;@testing-library/jest-dom/jest-globals&quot;;</pre><p>Now typescript is happy!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/926/1*t4Q73L0weuaiU5SgOEc9qg.png" /></figure><h3>Afterword</h3><p>Ideally, we would like to not have to import @jest/globals and @testing-library/jest-dom/jest-globals globally so we don’t have to do it in everywhere, but if we do that, it breaks cypress component test files when doing typescript checks…thus this workaround.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=87ca65ad3233" width="1" height="1" alt=""><hr><p><a href="https://medium.com/nexl-engineering/how-to-fix-cypress-component-test-expect-function-conflict-with-jest-react-testing-library-expect-87ca65ad3233">How to fix cypress component test expect function conflict with Jest/React testing library expect</a> was originally published in <a href="https://medium.com/nexl-engineering">NEXL Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[OAuth Authentication in Flutter App and Set Up GraphQL with Authentication Token]]></title>
            <link>https://medium.com/nexl-engineering/oauth-authentication-in-flutter-app-and-set-up-graphql-with-authentication-token-d2b3f65fee2e?source=rss-eabc66769ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/d2b3f65fee2e</guid>
            <category><![CDATA[flutter-oauth]]></category>
            <category><![CDATA[flutter-graphql]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Backspace Catalyst]]></dc:creator>
            <pubDate>Fri, 09 Dec 2022 11:13:42 GMT</pubDate>
            <atom:updated>2022-12-09T11:13:42.359Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>How to implement OAuth login in Flutter app and set up GraphQL client with authentication token coming back from OAuth</strong></h4><p>In this post, we will cover:</p><ol><li><strong>Implement OAuth authentication in Flutter app</strong></li><li><strong>Set up GraphQL client with authentication token coming back from OAuth</strong></li></ol><p>If you are interested in GraphQL with flutter, check out my other post:</p><p><a href="https://medium.com/nexl-engineering/flutter-graphql-type-generation-and-how-to-use-generated-types-fragments-in-widgets-and-widget-ee18969bd6d9"><em>Flutter GraphQL Type Generation and How to Use Generated Types/Fragments in Widgets and Widget Tests</em></a></p><p>In our example, the end result looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Kz6f3Zuajo1ajPkymjTCbQ.png" /></figure><h3>TL;NR;</h3><p>your_project/<br> — lib/<br> — — auth/<br> — — — models/<br> — — — — <a href="https://gist.github.com/mayyyc/d25a90f4a678d411fc3df23c7c6cc2d6">oauth_id_token.dart</a><br> — — — — oauth_id_token.g.dart // generated file<br> — — — screens/<br> — — — — <a href="https://gist.github.com/mayyyc/5291f5e35e1727a15bb4f94589b937c4">login_screen.dart</a><br> — — — services/<br> — — — — <a href="https://gist.github.com/mayyyc/8e5bc8703fcd7d5ee716e8e259a8cbdf">auth_service.dart</a><br> — — — widgets/<br> — — — — <a href="https://gist.github.com/mayyyc/2a6f72e4a997d4209983bf88b827ec3d">auth_provider.dart</a><br> — — — — <a href="https://gist.github.com/mayyyc/69b3cc9eadbf38bbb4f00490f35c4d92">graphql_provider.dart</a><br> — — tasks/<br> — — — screens/<br> — — — — <a href="https://gist.github.com/mayyyc/d4329ebf590d92301afe8cd0e95b8789">tasks_screen.dart</a><br> — — utils/<br> — — — <a href="https://gist.github.com/mayyyc/65e70afe9c765bbb823930583e1b2b3f">constants.dart</a><br> — — <a href="https://gist.github.com/mayyyc/b04c58279d0d53ea2da66a3563e09def">main.dart</a></p><h3><strong>1. Implement OAuth authentication in Flutter app</strong></h3><p>This <a href="https://auth0.com/blog/flutter-authentication-authorization-with-auth0-part-1-adding-authentication-to-an-app/#Implement-Login">post</a> explains everything very well, if you want to know how oauth authentication works and why we do each step, check it out. I followed it for the most part but we don’t use Auth0 so it’s slightly different, also we have a slightly different flow.</p><p>Here I will not try to explain everything and only focus on the solution.</p><p>The flow is as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_L0xGYdnWD97jqud0XVzCA.png" /></figure><h4>Packages</h4><p><strong>dependencies:</strong> flutter_appauth / flutter_secure_storage / json_annotation</p><p><strong>dev_dependencies:</strong> build_runner / json_serializable</p><pre>flutter pub add flutter_appauth flutter_secure_storage json_annotation<br>flutter pub add -d build_runner json_serializable</pre><h4>Usage</h4><p>auth_service.dart interacts with OAuth provider.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/64dddac07ccc0591e8878ba4e55f04ed/href">https://medium.com/media/64dddac07ccc0591e8878ba4e55f04ed/href</a></iframe><p><strong>Line 20</strong>: init() takes the refresh token stored and calls the OAuth provider to get the access token and store it in the storage.</p><p><strong>Line 43</strong>: login() is very straight forward, it tries to log in with OAuth provider and store access token and refresh token in the storage.</p><p><em>Note: you can find all the imported files in the TL;NR; section, I will not go into details here.</em></p><p>Then we create auth_provider.dart to handle the authentication state.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5485b49c8018a562e804d3a9e6bd6ed4/href">https://medium.com/media/5485b49c8018a562e804d3a9e6bd6ed4/href</a></iframe><p><strong>line 48</strong>: when the widget is initialised, call AuthService.init() to log in with refresh token.</p><p><strong>line 57–63</strong>: if the user is logged in, show child widget. Otherwise show login screen.</p><p>login_screen.dart allows user to login with OAuth.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/779f08154a4c1336e6c1b39d9eb49457/href">https://medium.com/media/779f08154a4c1336e6c1b39d9eb49457/href</a></iframe><p><strong>Line 52:</strong> when user press login button, call AuthService.login() to login with OAuth. If successful, set state from AuthProvider to logged in and user will see logged in page.</p><p>In main.dart, we wrap AuthProvider around the screen user should see when they are logged in.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5d2d32cf2a1f8d1b37be399f2077e862/href">https://medium.com/media/5d2d32cf2a1f8d1b37be399f2077e862/href</a></iframe><p><strong>Line 18:</strong> AuthProvider should be outside GraphqlProvider, and then inside it’s the widget that calls GraphQL queries.</p><h3><strong>2. Set up GraphQL client with authentication token coming back from OAuth</strong></h3><p>Once login is successful, we should have an access token and we pass the token to our GraphQL client in graphql_provider.dart as below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6733e1f516fa532cbaedd82b0f1a6bcd/href">https://medium.com/media/6733e1f516fa532cbaedd82b0f1a6bcd/href</a></iframe><p><strong>Line 14:</strong> take the stored access token and pass to GraphQL client.</p><p>Now we can call GraphQL from widgets inside GraphqlProvider, for example, we have tasks_screen.dart here.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/44ce4c21cb54e753704ce50b41495d2c/href">https://medium.com/media/44ce4c21cb54e753704ce50b41495d2c/href</a></iframe><p>That’s all, if you would like to know more about GraphQL set up, check out <a href="https://medium.com/nexl-engineering/flutter-graphql-type-generation-and-how-to-use-generated-types-fragments-in-widgets-and-widget-ee18969bd6d9"><em>Flutter GraphQL Type Generation and How to Use Generated Types/Fragments in Widgets and Widget Tests</em></a></p><p>Thanks for reading, hope this post can save some of your struggle =)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d2b3f65fee2e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/nexl-engineering/oauth-authentication-in-flutter-app-and-set-up-graphql-with-authentication-token-d2b3f65fee2e">OAuth Authentication in Flutter App and Set Up GraphQL with Authentication Token</a> was originally published in <a href="https://medium.com/nexl-engineering">NEXL Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter GraphQL Type Generation and How to Use Generated Types/Fragments in Widgets and Widget…]]></title>
            <link>https://medium.com/nexl-engineering/flutter-graphql-type-generation-and-how-to-use-generated-types-fragments-in-widgets-and-widget-ee18969bd6d9?source=rss-eabc66769ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee18969bd6d9</guid>
            <category><![CDATA[flutter-artemis]]></category>
            <category><![CDATA[flutter-test]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[flutter-graphql]]></category>
            <dc:creator><![CDATA[Backspace Catalyst]]></dc:creator>
            <pubDate>Fri, 09 Dec 2022 05:15:37 GMT</pubDate>
            <atom:updated>2022-12-09T11:15:38.514Z</atom:updated>
            <content:encoded><![CDATA[<h3>Flutter GraphQL Type Generation and How to Use Generated Types/Fragments in Widgets and Widget Tests</h3><h4>Using Artemis to generate GraphQL types in Flutter app to make passing data and widget testing easier with working example</h4><p>In this post, we will cover:</p><ol><li><strong>Set up GraphQL client in Flutter app</strong></li><li><strong>Use Artemis to generate GraphQL types</strong></li><li><strong>Use Fragments in GraphQL</strong></li><li><strong>Parse custom GraphGL types to Dart types</strong></li><li><strong>Save and run scripts from pubspec.yaml</strong></li><li><strong>Create data from generated types for widget testing</strong></li></ol><p>In our example, the end result looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dywmnPtUErdcWWmWXG0bRg.jpeg" /></figure><h3>1. Use GraphQL in Flutter app</h3><h4>Package</h4><p>graphql_flutter: <a href="https://pub.dev/packages/graphql_flutter">Documentation</a></p><pre>flutter pub add graphql_flutter</pre><h4>Set up</h4><p>Create a widget <a href="https://gist.github.com/mayyyc/69b3cc9eadbf38bbb4f00490f35c4d92">graphql_provider.dart</a> as below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6733e1f516fa532cbaedd82b0f1a6bcd/href">https://medium.com/media/6733e1f516fa532cbaedd82b0f1a6bcd/href</a></iframe><p><strong>Line 13</strong>: update the path to your GraphQL API endpoint.</p><p><strong>Line 14–16:</strong> optional, only if you have authentication and need to pass in token to your GraphQL API. If you would like to know more about flutter OAuth authentication, check out my other post <a href="https://medium.com/nexl-engineering/oauth-authentication-in-flutter-app-and-set-up-graphql-with-authentication-token-d2b3f65fee2e"><em>OAuth Authentication in Flutter App and Set Up GraphQL with Authentication Token</em></a><em>.</em></p><p><strong>Line 21–34:</strong> also optional, if you leave it out, it will use GraphQL cache. I have noCache there because somehow it doesn’t work with fragments, which I will talk about in section 3.</p><h4>Usage</h4><p>In <a href="https://gist.github.com/mayyyc/b04c58279d0d53ea2da66a3563e09def">main.dart</a>, wrap GraphqlProvider around your screen widgets (<strong>line 19–21</strong>).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5d2d32cf2a1f8d1b37be399f2077e862/href">https://medium.com/media/5d2d32cf2a1f8d1b37be399f2077e862/href</a></iframe><p>Now you can use queries/mutation in the child widgets, check out <a href="https://pub.dev/packages/graphql_flutter#query">here</a> to find out how to do it. But we are going to do it slightly different because we are going to use Artemis.</p><h3>2. Use Artemis to generate GraphQL types</h3><p><a href="https://medium.com/@v.ditsyak/ultimate-toolchain-to-work-with-graphql-in-flutter-13aef79c6484">This post</a> and <a href="https://ramyakmehra.medium.com/graphql-type-generation-in-flutter-c4e9436d6233">another one</a> explains very well why we need each package and why we do each step, have a read if you like. Here I will just focus on what exactly needs to be done.</p><h4><strong>Packages</strong></h4><p>artemis / build_runner / json_serializable</p><pre>flutter pub add artemis<br>flutter pub add -d build_runner json_serializable</pre><h4>Set up</h4><p>create <a href="https://gist.github.com/mayyyc/ea77b16237995b4f0c528a19a2b9c284">build.yaml</a> in your project root as below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a39e2fe742d99b473ba2ee5a02021649/href">https://medium.com/media/a39e2fe742d99b473ba2ee5a02021649/href</a></iframe><p><strong>Line 5:</strong> all the queries, mutations, anything ending with .gql will go inside your_project/graphql folder.</p><p><strong>Line 6:</strong> You need to get schema file that tells artemis what all the types look like from your GraphQL server, I put it in your_project/tmp/introspection.gql.</p><p><strong>Line 10:</strong> specify where fragment files are, you will need this if you use fragments. In my example, any file ending with .fragment.gql in your_project/graphql folder. Will explain in section 3.</p><p><strong>Line 15–21</strong>: optional, only if you have custom GraphQL type that you want to parse to specific dart type, will explain in section 4.</p><h4>Usage</h4><p>In your_project/graphql folder, create a file for our first query.</p><pre># /graphql/task/tasks.query.gql<br>query Tasks($filter: TaskFiltering, $page: Int = 1, $perPage: Int = 10) {<br>  tasks(filter: $filter, page: $page, perPage: $perPage) {<br>    entries {<br>      ...TaskListItem<br>    }<br>    pageInfo {<br>      totalEntries<br>    }<br>  }<br>  currentUser {<br>    id<br>    email<br>  }<br>}</pre><pre># /graphql/task/task_list_item.fragment.gql<br>fragment TaskListItem on Task {<br>  id<br>  title<br>  description {<br>    plainText<br>  }<br>  dueOn<br>  completedAt<br>  contact {<br>    ...ContactName<br>  }<br>  company {<br>    ...CompanyName<br>  }<br>  assignedTo {<br>    ...EmployeeName<br>  }<br>  createdBy {<br>    ...EmployeeName<br>  }<br>}</pre><pre># /graphql/contact/contact_name.fragment.gql<br>fragment ContactName on Contact {<br>  id<br>  primaryEmail<br>  info {<br>    firstName<br>    lastName<br>  }<br>}</pre><p>Run script below and you will see files generated in your_project/lib/__generated__/graphql_types.dart.</p><pre>flutter pub run build_runner build --delete-conflicting-outputs</pre><p>Now we are ready to call the query in our widget <a href="https://gist.github.com/mayyyc/d4329ebf590d92301afe8cd0e95b8789">tasks_screen.dart</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/44ce4c21cb54e753704ce50b41495d2c/href">https://medium.com/media/44ce4c21cb54e753704ce50b41495d2c/href</a></iframe><p><strong>Line 18–26:</strong> TaskQuery is coming from generated code /__generated__/graphql_types.graphql.dart, as well as TasksArguments, TaskFiltering, etc.</p><p><strong>Line 29–36:</strong> the result coming from GraphQL server is json and we parse into a dart type Tasks$Query$TaskEntries here.</p><h3><strong>3. Use Fragments in GraphQL and Flutter widgets</strong></h3><p>Okay now the question is, we render the tasks in TaskList widget, but what type is tasks.</p><p>The answer is, TaskListItemMixin (see line 8).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7479c3c76ec893e72bf29357efece808/href">https://medium.com/media/7479c3c76ec893e72bf29357efece808/href</a></iframe><p>And line 10 here in task_list_item.dart.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/64ba432518a1542e6cd9453dc92f362e/href">https://medium.com/media/64ba432518a1542e6cd9453dc92f362e/href</a></iframe><p>Another thing is, somehow fragment just doesn’t work with GraphQL cache, here is the <a href="https://github.com/comigor/artemis/issues/393">github issue</a> about it. So we have to disable cache, if you scroll back up to graphql_provider.dart, you will see in Line 21–34.</p><h3><strong>4. Parse custom GraphGL types to Dart types</strong></h3><p>In our GraphQL backend, we have a type ISO8601DateTime, and I want it to be converted to dart DateTime, we can achieve this by using custom parser.</p><p>In build.yaml line 15–21, we specify which type we want to convert and which parser we want to use.</p><p>Then we create iso8601_date_time_coercers.dart in /your_project/lib/utils/coercers folder as below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cf0a35d63e9ca42f01c0cecfa57e0085/href">https://medium.com/media/cf0a35d63e9ca42f01c0cecfa57e0085/href</a></iframe><p>Now all the ISO8601DateTime data will be dart&#39;s DateTime type. Yay.</p><h3><strong>5. Save and run scripts from pubspec.yaml</strong></h3><p>Running flutter pub run build_runner build --delete-conflicting-outputs is just too clumbsome and it is impossible to remember the command. So let’s add a tool so we can run scripts alias like in package.json.</p><h4>Package</h4><p>rps: <a href="https://github.com/gonuit/rps">Documentation</a></p><pre>dart pub global activate rps</pre><h4>Set up</h4><p>In your pubspec.yaml, add scripts like below.</p><pre>dependencies:<br>  ...<br>scripts:<br>  codegen: flutter pub run build_runner build --delete-conflicting-outputs</pre><p>Now, we can run rps codegen.</p><h3><strong>6. Create data from generated types for widget testing</strong></h3><p>Now the most important thing of a project, testing! How can we create some tasks for our widget tests?</p><p>Here we are, we can create t<a href="https://gist.github.com/mayyyc/cd1e8d4ec9216fc9e3f9e09b2bb93da0">ask_list_item_factory.dart</a> as below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a5a9fc778ce44ea16ec5f1dfed60e1de/href">https://medium.com/media/a5a9fc778ce44ea16ec5f1dfed60e1de/href</a></iframe><p>And here is how we use it in <a href="https://gist.github.com/mayyyc/c92428af70e185a6a6fc1cad1cb44cfd">task_list_item.test.dart</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0a6e0937e7af69381490a38f7f6c2525/href">https://medium.com/media/0a6e0937e7af69381490a38f7f6c2525/href</a></iframe><p><strong>Line 9:</strong> initialise our factory.</p><p><strong>Line 16:</strong> create a task item using factory.</p><p>This is it, hope this helps =)</p><h3><strong>Summary</strong></h3><p>your_project/<br> — graphql/ <br> — — contact/ <br> — — — <a href="https://gist.github.com/mayyyc/a0679bc93a196184242ab8cbe72e608e">contact_name.fragment.gql</a><br> — — task/<br> — — — <a href="https://gist.github.com/mayyyc/83b4bf528fedb958a91727a7b29cd69d">tasks.query.gql</a><br> — — — <a href="https://gist.github.com/mayyyc/eb8642f2bde96520b14b11deb03869b0">task_list_item.fragment.gql</a><br> — lib/<br> — — __generated__/<br> — — — graphql_types.graphql.dart // code generated by artemis<br> — — auth/<br> — — — widgets/<br> — — — — <a href="https://gist.github.com/mayyyc/69b3cc9eadbf38bbb4f00490f35c4d92">graphql_provider.dart</a><br> — — task/<br> — — — screens/<br> — — — — <a href="https://gist.github.com/mayyyc/d4329ebf590d92301afe8cd0e95b8789">tasks_screen.dart</a><br> — — — widgets/<br> — — — — <a href="https://gist.github.com/mayyyc/c51f2e030d0a42509dc384c047ef1cd2">task_list.dart</a><br> — — — — <a href="https://gist.github.com/mayyyc/e87324bac908843f4da441b9f6722cbe">task_list_item.dart</a><br> — — utils/<br> — — — coercers/<br> — — — — <a href="https://gist.github.com/mayyyc/0ac815e2712897e8241973c47d99029a">iso08601_date_time_coercers.dart</a><br> — test/<br> — — task/<br> — — — widgets/<br> — — — — <a href="https://gist.github.com/mayyyc/cd1e8d4ec9216fc9e3f9e09b2bb93da0">task_list_item_factory.dart</a><br> — — — — <a href="https://gist.github.com/mayyyc/c92428af70e185a6a6fc1cad1cb44cfd">task_list_item.test.dart</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee18969bd6d9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/nexl-engineering/flutter-graphql-type-generation-and-how-to-use-generated-types-fragments-in-widgets-and-widget-ee18969bd6d9">Flutter GraphQL Type Generation and How to Use Generated Types/Fragments in Widgets and Widget…</a> was originally published in <a href="https://medium.com/nexl-engineering">NEXL Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to use Material UI MobileStepper to make a carousel view with multiple item per view]]></title>
            <link>https://medium.com/nexl-engineering/how-to-use-material-ui-mobilestepper-to-make-a-carousel-view-with-multiple-item-per-view-85598eb2f05f?source=rss-eabc66769ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/85598eb2f05f</guid>
            <category><![CDATA[material-ui]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Backspace Catalyst]]></dc:creator>
            <pubDate>Sat, 10 Sep 2022 07:03:50 GMT</pubDate>
            <atom:updated>2022-09-10T07:03:50.551Z</atom:updated>
            <content:encoded><![CDATA[<p>Mui’s mobile stepper is great if we want to make a <a href="https://mui.com/material-ui/react-stepper/#text-with-carousel-effect">carousel view</a>, but what if we want to show multiple item per view? It’s pretty simple too. In this article we will create a component &lt;SwipeableMobileStepper /&gt; which takes an array of elements we want to turn into a carousel view children: JSX.Element[], and itemsPerView so we can render whatever number of items per view as we want.</p><h3>Preview</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*PV1aMDLSoIt5f1kdgzie0Q.gif" /></figure><h3>How</h3><p>We are going to start with this <a href="https://mui.com/material-ui/react-stepper/#text-with-carousel-effect">example</a> in mui’s documentation, only a few lines of changes are needed to turn it into our generic carousel component.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*FWjAVM2pE6T_Pv0Y6FHIGQ.gif" /></figure><h4>TL;NR</h4><p><a href="https://gist.github.com/mayyyc/82682af83b20f8684d6b71410f514943">Gist</a></p><h4>Step 1</h4><p>In our component SwipeableMobileStepper.tsx, pass in the props:</p><pre>interface ISwipeableMobileStepperProps {<br>  children: JSX.Element[]; // the items to turn into carousel<br>  itemsPerView: number; // how many items we want in each view<br>}</pre><h4>Step 2</h4><p>Calculate how many steps there should be(line 18):</p><pre>const maxSteps = Math.ceil(children.length / itemsPerView);</pre><h4>Step 3</h4><p>Render a container element for each step (line 39):</p><pre>{[...Array(maxSteps)].map((_, index) =&gt; {<br>          return (<br>            &lt;Box<br>              key={`step-${index}`}<br>              sx={{<br>                display: &quot;flex&quot;,<br>                alignItems: &quot;stretch&quot;,<br>                justifyContent: &quot;space-evenly&quot;,<br>              }}<br>            &gt;<br>              {...} // this is our next step<br>            &lt;/Box&gt;<br>          );<br>        })}</pre><h4>Step 4</h4><p>Render {itemsPerView} items within each step container (line 49):</p><pre>{children.slice(<br>                  index * itemsPerView,<br>                  index * itemsPerView + itemsPerView<br>                )<br>                .map((child, childIndex) =&gt; {<br>                  return (<br>                    &lt;Box sx={{ mx: 1 }} key={`step-${index}-${childIndex}`}&gt;<br>                      {React.cloneElement(child as JSX.Element, {})}<br>                    &lt;/Box&gt;<br>                  );<br>                })}</pre><p>That’s it. There we have a generic component that we can pass in the elements we want to turn into a carousel view and how many elements we want to show per view. Enjoy coding =)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a907494c0127536c7e8904d3990babff/href">https://medium.com/media/a907494c0127536c7e8904d3990babff/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a907494c0127536c7e8904d3990babff/href">https://medium.com/media/a907494c0127536c7e8904d3990babff/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=85598eb2f05f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/nexl-engineering/how-to-use-material-ui-mobilestepper-to-make-a-carousel-view-with-multiple-item-per-view-85598eb2f05f">How to use Material UI MobileStepper to make a carousel view with multiple item per view</a> was originally published in <a href="https://medium.com/nexl-engineering">NEXL Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cypress component test to assert function called with deep nested object value]]></title>
            <link>https://medium.com/nexl-engineering/cypress-component-test-to-assert-function-called-with-deep-nested-object-value-21b50bdf8a2f?source=rss-eabc66769ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/21b50bdf8a2f</guid>
            <category><![CDATA[cypress-testing]]></category>
            <category><![CDATA[cypress-component-testing]]></category>
            <category><![CDATA[react-unit-test]]></category>
            <dc:creator><![CDATA[Backspace Catalyst]]></dc:creator>
            <pubDate>Sun, 21 Aug 2022 06:28:58 GMT</pubDate>
            <atom:updated>2022-08-21T06:28:58.796Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/818/1*QlMyuuag1Pu6aAptHrmwrg.png" /></figure><p>When doing cypress component test on a form, I came across an issue that the onSubmit function is called with a deep nested object. The object looks something like this:</p><pre>{<br>  relationshipPartner: {<br>    id: string; <br>    email: string; <br>    info: { firstName: string; lastName:string; }<br>  };<br>  ...moreProperties,<br>}</pre><p>I wanted to assert that onSubmit function is called with the correct relationship partner email. It was really hard to use .toEqual(). When I had the order of the properties wrong it returns false and I always had to write out the whole object even when I only care about the relationship partner email.</p><p>It was quite a struggle but in the end I had a solution looks like this:</p><pre>it(&quot;should submit with relationship partner&quot;, () =&gt; {<br>    const onSubmit = cy.stub().as(&quot;onSubmit&quot;);<br>    mount(<br>      &lt;AddCompanyRelationshipPartner<br>        onSubmit={onSubmit}<br>      /&gt;<br>    );<br>    cy.findByRole(&quot;button&quot;, { name: /Update Relationship Partner/i }).click();<br>    cy.findAllByLabelText(/relationship partner/i)<br>      .first()<br>      .type(&quot;ellen{enter}&quot;);<br>    cy.findByRole(&quot;button&quot;, { name: /Save/i }).click();<br>    <strong>cy.get(&quot;</strong><a href="http://twitter.com/onSubmit"><strong>@onSubmit</strong></a><strong>&quot;).should((i) =&gt; {<br>      const spy = i[&quot;getCalls&quot;]();<br>      const { args } = spy[0];<br>expect(args[0].relationshipPartner.email).to.equal(&quot;</strong><a href="/service/mailto:ellen@nexl.io"><strong>ellen@nexl.io</strong></a><strong>&quot;);<br>    });</strong><br>  });</pre><p>Hope this helps =)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=21b50bdf8a2f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/nexl-engineering/cypress-component-test-to-assert-function-called-with-deep-nested-object-value-21b50bdf8a2f">Cypress component test to assert function called with deep nested object value</a> was originally published in <a href="https://medium.com/nexl-engineering">NEXL Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Row grouping when you have cell renderer — AG Grid with React and Typescript]]></title>
            <link>https://medium.com/nexl-engineering/row-grouping-when-you-have-cell-renderer-ag-grid-with-react-and-typescript-cabba1722952?source=rss-eabc66769ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/cabba1722952</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[ag-grid]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Backspace Catalyst]]></dc:creator>
            <pubDate>Fri, 03 Dec 2021 06:34:17 GMT</pubDate>
            <atom:updated>2021-12-03T06:38:46.811Z</atom:updated>
            <content:encoded><![CDATA[<h3>Row grouping when you have cell renderer — AG Grid with React and Typescript</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a_pSQR9V_q9gQfJu_rmZ7w.png" /><figcaption>AG Grid row grouping with cell renderer</figcaption></figure><p>More posts on AG Grid with React and Typescript:</p><ul><li><a href="https://medium.com/nexl-engineering/rendering-d3-chart-in-ag-grid-cell-ag-grid-with-react-and-typescript-2ed5ee848763">Rendering d3 chart in AG Grid cell</a></li><li><a href="https://medium.com/nexl-engineering/rendering-columns-dynamically-ag-grid-with-react-and-typescript-f35c0feaf67">Rendering columns dynamically</a></li><li><a href="https://medium.com/nexl-engineering/row-grouping-when-you-have-cell-renderer-ag-grid-with-react-and-typescript-cabba1722952">Row grouping when you have cell renderer</a></li></ul><h3>The Problem</h3><p>Row grouping doesn’t work when your data are not simple strings but complex objects, and it is not straight forward how to implement it from the documentation. So hopefully my struggle can make your life a little easier now.</p><h3>The Solution</h3><h4>Key 1 — groupColumnCellRenderer</h4><p>In gridOptions, we should have something like below. It specifies how you want to render the group label. And you can make it return a fancy component if you like, the only thing is it doesn’t contain row data but only the value of the column you group by. Try console.log(props) in the cell renderer function, you will see what information you have on the group.</p><pre>{<br>  ...,<br>  frameworkComponents: {<br>    ...,<br>    <strong>groupColumnCellRenderer: (props) =&gt; props.value,</strong><br>    ...<br>  },<br>  autoGroupColumnDef: {<br>    cellRendererParams: {<br>      <strong>innerRenderer: &quot;groupColumnCellRenderer&quot;,</strong><br>    },<br>    pinned: &quot;left&quot;,<br>  },<br>  rowGroupPanelShow: &quot;always&quot;,<br>  ...<br>}</pre><h4>Key 2 — valueGetter</h4><p>You need valueGetter in your columnDef when the cell value is not a simple value of string or number. For example, you have a row like this:</p><pre>{<br>  company: {id: &quot;000&quot;, domain: &quot;company.com&quot;, name: &quot;good company&quot;}<br>}</pre><p>And in you columnDef, you will need to have a valueGetter like this:</p><pre>{<br>  field: &quot;company&quot;, <br><strong>  valueGetter: (props) =&gt; props.data.company.domain, </strong><br>  cellRenderer: &quot;companyCellRenderer&quot;<br>}</pre><p>And in &lt;CompanyCellRenderer /&gt;, you have to do it again:</p><pre>export const CompanyCellRenderer = (props: ICellRendererParams) =&gt; {<br>  if (!props.data) return null;<br>  const company = props.data.company;<br>  return (<br>    &lt;div&gt;<br>      &lt;p&gt;{company.domain}&lt;/p&gt;<br>      &lt;p&gt;{company.name}&lt;/p&gt;<br>    &lt;/div&gt;<br>  );<br>};</pre><p>I found it quite repetitive to do it for every column so in the end I refactor the row to something like this:</p><pre>{<br>  contact: each.contact.name,<br>  company: each.company.domain, // this saves us writing valueGetter<br>  ...,<br>  <strong>rawData: each // and we pass everything in here for cell renderers</strong><br>}</pre><p>And in &lt;CompanyCellRenderer /&gt;:</p><pre>export const CompanyCellRenderer = (props: ICellRendererParams) =&gt; {<br>  if (!props.data) return null;<br>  <strong>const company = props.data.rawData.company;</strong><br>  return (<br>    &lt;div&gt;<br>      &lt;p&gt;{company.domain}&lt;/p&gt;<br>      &lt;p&gt;{company.name}&lt;/p&gt;<br>    &lt;/div&gt;<br>  );<br>};</pre><p>In this way, we won’t need to write any value getters.</p><h4>Key 3 — cell renderer</h4><p>This took me half day to figure out, basically in &lt;CompanyCellRenderer /&gt;, you need to check if props.data exists or not. The reason for this is the group row doesn’t have props.data any only has props.value that we mentioned in the first key point. And the value is the value of which you group by. Say you group by company, one of props.value will be “company.com”(domain of the company).</p><pre>export const CompanyCellRenderer = (props: ICellRendererParams) =&gt; {<br><strong>  if (!props.data) return null;</strong><br>  const company = props.data.rawData.company;<br>  return (<br>    &lt;div&gt;<br>      &lt;p&gt;{company.domain}&lt;/p&gt;<br>      &lt;p&gt;{company.name}&lt;/p&gt;<br>    &lt;/div&gt;<br>  );<br>};</pre><p>Check out the raw file here:</p><p><a href="https://gist.github.com/mayyyc/d49c3b57b1019b2a7052dc07af517cdd">gridOptions.ts</a><br><a href="https://gist.github.com/mayyyc/a22d3ccc0bbde3744ec1921c9f4c31c7">rowData.ts</a><br><a href="https://gist.github.com/mayyyc/b4696702c706eb7bca54dae4a3e2ebe1">CompanyCellRenderer.tsx</a></p><p>More posts on AG Grid with React and Typescript:</p><ul><li><a href="https://medium.com/nexl-engineering/rendering-d3-chart-in-ag-grid-cell-ag-grid-with-react-and-typescript-2ed5ee848763">Rendering d3 chart in AG Grid cell</a></li><li><a href="https://medium.com/nexl-engineering/rendering-columns-dynamically-ag-grid-with-react-and-typescript-f35c0feaf67">Rendering columns dynamically</a></li><li><a href="https://medium.com/nexl-engineering/row-grouping-when-you-have-cell-renderer-ag-grid-with-react-and-typescript-cabba1722952">Row grouping when you have cell renderer</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cabba1722952" width="1" height="1" alt=""><hr><p><a href="https://medium.com/nexl-engineering/row-grouping-when-you-have-cell-renderer-ag-grid-with-react-and-typescript-cabba1722952">Row grouping when you have cell renderer — AG Grid with React and Typescript</a> was originally published in <a href="https://medium.com/nexl-engineering">NEXL Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rendering columns dynamically — AG Grid with React and Typescript]]></title>
            <link>https://medium.com/nexl-engineering/rendering-columns-dynamically-ag-grid-with-react-and-typescript-f35c0feaf67?source=rss-eabc66769ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/f35c0feaf67</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[ag-grid]]></category>
            <dc:creator><![CDATA[Backspace Catalyst]]></dc:creator>
            <pubDate>Fri, 03 Dec 2021 04:47:30 GMT</pubDate>
            <atom:updated>2021-12-03T06:38:11.805Z</atom:updated>
            <content:encoded><![CDATA[<h3>Rendering columns dynamically — AG Grid with React and Typescript</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*us475JjiBsUFbDFaYA8yVA.png" /><figcaption>AG Grid with dynamic columns</figcaption></figure><p>More posts on AG Grid with React and Typescript:</p><ul><li><a href="https://medium.com/nexl-engineering/rendering-d3-chart-in-ag-grid-cell-ag-grid-with-react-and-typescript-2ed5ee848763">Rendering d3 chart in AG Grid cell</a></li><li><a href="https://medium.com/nexl-engineering/rendering-columns-dynamically-ag-grid-with-react-and-typescript-f35c0feaf67">Rendering columns dynamically</a></li><li><a href="https://medium.com/nexl-engineering/row-grouping-when-you-have-cell-renderer-ag-grid-with-react-and-typescript-cabba1722952">Row grouping when you have cell renderer</a></li></ul><h3>The problem</h3><p>In our grid, we want have some dynamic columns and not every row of data has all the columns. So in the &lt;Grid /&gt; component, we pass in the custom field schema to specify what fields are on the grid, as well as the data with custom field values.</p><pre>//Grid.tsx</pre><pre>interface IGridProps {<br>  data: CompanyListMemberRowFragment[];<br>  customFieldDefs: CustomFieldSchema[];<br>}</pre><pre>export const Grid = ({<br>    data,<br>    customFieldDefs,<br>}: IGridProps) =&gt; {<br>   ... <br>   &lt;AgGridReact {...} /&gt;<br>}</pre><p>Custom field schema looks like this:</p><pre>export type CustomFieldSchema = {<br>  id: string;<br>  name: string;<br>  options: object[];<br>  type: string;<br>};</pre><p>Data looks like this:</p><pre>export type CompanyListMemberRowFragment = { <br>  id:string;<br>  companyName:string;<br>  domain:string;<br>  ...<br>  customFields: {<br>    id: string;<br>    name: string;<br>    value: WhateverValue;<br>    type: string;<br>  }[];<br>};</pre><h4>Problem 1</h4><p>columnDefs is dynamic depending on the CustomFieldSchema[] we pass in.</p><h4>Problem 2</h4><p>In data, customFields value comes with different types, each needs a different cell renderer.</p><h3>The solution</h3><p>For columnDefs:</p><pre>{<br>  ...,<br>  {<br>    field: ...,<br>  },<br>  ...customFieldDefs.map((customFieldDef) =&gt; ({<br>    field: customFieldDef.name,<br>    valueGetter: (params) =&gt; {<br>      if (!params.data) return undefined;<br>      const field = params.data[customFieldDef.name];<br>      return field &amp;&amp; getCustomFieldStringValue(field);<br>    },<br>    cellRenderer: &quot;customFieldCellRenderer&quot;,<br>  })),<br>  ...<br>}</pre><p>Check out full file <a href="https://gist.github.com/mayyyc/68f850377460e0d967dd87c9484e113e">here</a>.</p><p>For rowData:</p><pre>rowData = data.map((each) =&gt; {<br>    const { id, domain, ..., customFields } = each;<br>    const row = {<br>      id,<br>      domain,<br>    };<br><strong>    customFields?.forEach((customField) =&gt; {<br>      row[customField.name] = customField;<br>    });</strong><br>    return row;<br>  });</pre><p>Full file <a href="https://gist.github.com/mayyyc/a22d3ccc0bbde3744ec1921c9f4c31c7">here</a>.</p><p>Custom field cell renderer:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/27667e791ab14cb9c9ac6b315112a43a/href">https://medium.com/media/27667e791ab14cb9c9ac6b315112a43a/href</a></iframe><p>Grid component:</p><pre>interface IGridProps {<br>  listMembers: CompanyListMemberRowFragment[];<br>  customFields: CustomFieldSchema[];<br>}</pre><pre>export const Grid: React.FC&lt;IGridProps&gt; =<br>  ({<br>    listMembers,<br>    customFields,<br>  }) =&gt; {<br>    const rows = getCompanyListGridRows(listMembers);<br>    const [columnDefs, setColumnDefs] = useState&lt;any[]&gt;([]);<br>    useEffect(() =&gt; {<br>      setColumnDefs(getCompanyListGridColumns(customFields));<br>    }, [customFields]);<br>    return (<br>            &lt;AgGridReact<br>              gridOptions={gridOptions}<br>              columnDefs={columnDefs}<br>              rowData={rows}<br>            /&gt;<br>    );<br>  };</pre><p>Full file <a href="https://gist.github.com/mayyyc/a709d96f9c41ac4b49e26a6bd411b018">here</a>.</p><p>More posts on AG Grid with React and Typescript:</p><ul><li><a href="https://medium.com/nexl-engineering/rendering-d3-chart-in-ag-grid-cell-ag-grid-with-react-and-typescript-2ed5ee848763">Rendering d3 chart in AG Grid cell</a></li><li><a href="https://medium.com/nexl-engineering/rendering-columns-dynamically-ag-grid-with-react-and-typescript-f35c0feaf67">Rendering columns dynamically</a></li><li><a href="https://medium.com/nexl-engineering/row-grouping-when-you-have-cell-renderer-ag-grid-with-react-and-typescript-cabba1722952">Row grouping when you have cell renderer</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f35c0feaf67" width="1" height="1" alt=""><hr><p><a href="https://medium.com/nexl-engineering/rendering-columns-dynamically-ag-grid-with-react-and-typescript-f35c0feaf67">Rendering columns dynamically — AG Grid with React and Typescript</a> was originally published in <a href="https://medium.com/nexl-engineering">NEXL Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rendering d3 chart in AG Grid cell — AG Grid with React and Typescript]]></title>
            <link>https://medium.com/nexl-engineering/rendering-d3-chart-in-ag-grid-cell-ag-grid-with-react-and-typescript-2ed5ee848763?source=rss-eabc66769ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/2ed5ee848763</guid>
            <category><![CDATA[ag-grid]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[d3js]]></category>
            <dc:creator><![CDATA[Backspace Catalyst]]></dc:creator>
            <pubDate>Thu, 02 Dec 2021 23:35:43 GMT</pubDate>
            <atom:updated>2021-12-03T06:37:21.214Z</atom:updated>
            <content:encoded><![CDATA[<h3>Rendering d3 chart in AG Grid cell — AG Grid with React and Typescript</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*olqXdz64TWz7cKTkzybTJQ.png" /><figcaption>d3 chart in AG Grid cell</figcaption></figure><p>More posts on AG Grid with React and Typescript:</p><ul><li><a href="https://medium.com/nexl-engineering/rendering-d3-chart-in-ag-grid-cell-ag-grid-with-react-and-typescript-2ed5ee848763">Rendering d3 chart in AG Grid cell</a></li><li><a href="https://medium.com/nexl-engineering/rendering-columns-dynamically-ag-grid-with-react-and-typescript-f35c0feaf67">Rendering columns dynamically</a></li><li><a href="https://medium.com/nexl-engineering/row-grouping-when-you-have-cell-renderer-ag-grid-with-react-and-typescript-cabba1722952">Row grouping when you have cell renderer</a></li></ul><h3>The problem</h3><p>We want to have a d3 chart in our grid, so we have &lt;EngagementCellRenderer /&gt;, in which we have a d3 chart. (If you want to know how the d3 chart is implemented, check out <a href="https://medium.com/nexl-engineering/get-started-with-d3-and-react-hooks-creating-a-bar-chart-206a8ddcafd">this</a>)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2995d04adb84957e2e3181948852cf82/href">https://medium.com/media/2995d04adb84957e2e3181948852cf82/href</a></iframe><p>But soon we found the chart doesn’t get rendered, my guess is the rendering order. &lt;div id={`engagement-${id}`} /&gt; only gets rendered when the grid is rendered so drawChart() won’t be able to find the element to mount the chart on.</p><h3>The Solution</h3><p>Basically we want to run drawChart() only after the grid is rendered.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d74f0247ca58b73ec3c19fd7f195a06d/href">https://medium.com/media/d74f0247ca58b73ec3c19fd7f195a06d/href</a></iframe><p>In the &lt;Grid /&gt; component, we run drawChart() with each row when the grid is rendered, so we have the renderChart() and we mount it on onFirstDataRendered.</p><pre>onFirstDataRendered={renderChart}</pre><p>And for performance reason, we don’t want to run it on every row but only the rows that’s in the view. In renderChart(), we check</p><pre>document.querySelector(`#engagement-${member.company.id}`) &amp;&amp;          !document.querySelector(`#engagement-${member.company.id} svg`)</pre><p>So drawChart() only runs when the element is there and when the chart is not there yet. And then we have to run renderChart() every time someone scroll on the grid.</p><pre>onBodyScroll={renderChart}</pre><p>That’s it =)</p><p>More posts on AG Grid with React and Typescript:</p><ul><li><a href="https://medium.com/nexl-engineering/rendering-d3-chart-in-ag-grid-cell-ag-grid-with-react-and-typescript-2ed5ee848763">Rendering d3 chart in AG Grid cell</a></li><li><a href="https://medium.com/nexl-engineering/rendering-columns-dynamically-ag-grid-with-react-and-typescript-f35c0feaf67">Rendering columns dynamically</a></li><li><a href="https://medium.com/nexl-engineering/row-grouping-when-you-have-cell-renderer-ag-grid-with-react-and-typescript-cabba1722952">Row grouping when you have cell renderer</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2ed5ee848763" width="1" height="1" alt=""><hr><p><a href="https://medium.com/nexl-engineering/rendering-d3-chart-in-ag-grid-cell-ag-grid-with-react-and-typescript-2ed5ee848763">Rendering d3 chart in AG Grid cell — AG Grid with React and Typescript</a> was originally published in <a href="https://medium.com/nexl-engineering">NEXL Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 4. Authentication with Session Cookie — Building Outlook Add-in with React]]></title>
            <link>https://medium.com/nexl-engineering/part-4-authentication-with-session-cookie-building-outlook-add-in-with-react-6d6561f8cc77?source=rss-eabc66769ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/6d6561f8cc77</guid>
            <category><![CDATA[office-add-ins]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[outlook]]></category>
            <dc:creator><![CDATA[Backspace Catalyst]]></dc:creator>
            <pubDate>Sun, 25 Jul 2021 01:36:02 GMT</pubDate>
            <atom:updated>2021-07-25T01:36:41.971Z</atom:updated>
            <content:encoded><![CDATA[<h3>Part 4. Authentication with Session Cookie — Building Outlook Add-in with React</h3><p><strong>More posts on buiding Outlook add-in with React:</strong></p><ul><li><a href="https://medium.com/nexl-engineering/build-an-outlook-add-in-with-react-part-0-setting-up-the-project-ddbaef68349c"><em>Part 0. Setting up the project</em></a></li><li><a href="https://medium.com/nexl-engineering/building-an-outlook-add-in-with-react-part-1-getting-data-emails-contacts-from-office-api-bb48751d645b"><em>Part 1. Getting Mailbox Data from Office API</em></a></li><li><a href="https://medium.com/@mayyyyyyc/building-an-outlook-add-in-with-react-part-2-pinnable-task-pane-dc08411b5d55">Part 2. Pinnable Task Pane</a></li><li><a href="https://medium.com/@mayyyyyyc/part-3-open-link-from-a-ribbon-button-building-outlook-add-in-with-react-a49fc130810">Part 3. Open Link from a Ribbon Button</a></li><li><a href="https://medium.com/@mayyyyyyc/part-4-authentication-with-session-cookie-building-outlook-add-in-with-react-6d6561f8cc77">Part 4. Authentication with Session Cookie</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*_ehw3lYKmEpz5omXWCadew.png" /><figcaption>NEXL 360 login screen</figcaption></figure><p>For our add-in, we use session cookie for authentication as that’s what we use for our web app and we didn’t want to spend too much backend resource on this project to build another authentication like JWT.</p><p>Looking back, it would have been better if we have JWT authentication for</p><ul><li>we can store the token in the local storage (<a href="https://docs.microsoft.com/en-us/javascript/api/outlook/office.roamingsettings?view=outlook-js-preview">RoamingSettings</a>) so the users won’t have to log in again every time they restart their Outlook.</li><li>easier local development as we have backend server on port 4000 and add-in frontend server on port 3000 and there are some security settings on the session cookie that doesn’t work on another port even though we have set up proxy, and we haven’t been able to solve this issue yet.</li></ul><p>So, I would suggest you to use JWT authentication if you can, and I have a <a href="https://medium.com/nexl-engineering/how-to-use-jwt-authorization-in-react-native-app-with-graphql-ad49f33de9b7">post</a> on JWT with react-native app but it should be pretty similar.</p><p>This post is more about the authentication flow instead of what authentication method to use. Now let’s get into it.</p><h3>The flow</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zaHVy4Tu_ma9wMJhCaTQwg.png" /><figcaption>authentication flow</figcaption></figure><p>Our add-in is a stand-alone app and talks to the backend server via GraphQL. When a user loads the add-in, we send a GraphQL query (currentUser) to the server and if it returns the data we know the user is authenticated and we let them into the app dashboard. If the query returns an error we redirect the user to the login page.</p><p>As we want to reuse the web app login, we have a button on the login page that opens up the web app login page in a dialog (Outlook’s in-built browser, it won’t work with user’s default browser as we need to set the session cookie within Outlook). And user logs into our service in the dialog, and from the dialog we need to somehow let the add-in know so we can refresh the page and now the GraphQL query will succeed as the session cookie is set and user can start using the add-in.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DtO_IZht8slifmy2UuD_7g.gif" /><figcaption>login ui in action</figcaption></figure><h3>Log in in details</h3><p>In CurrentUserContext.tsx, we make the currentUser call, and if it returns error, we redirect the user to the login page.</p><pre>export const CurrentUserProvider: React.FC = ({ children }) =&gt; {<br>  const { data, error, loading } = useGetCurrentUserQuery({<br>    errorPolicy: &quot;all&quot;,<br>  });<br><strong>  if (error &amp;&amp; location.pathname !== LOGIN_PATH) {<br>    navigate(LOGIN_PATH);<br>    return &lt;&gt;&lt;/&gt;;<br>  }</strong><br>  return (<br>    &lt;CurrentUserContext.Provider<br>      value={{<br>        currentUser: data?.currentUser,<br>      }}<br>    &gt;<br>      {loading ? (<br>        &lt;div&gt;<br>          &lt;QueryState loading loadingCopy=&quot;Logging in...&quot; /&gt;<br>        &lt;/div&gt;<br>      ) : (<br>        children<br>      )}<br>    &lt;/CurrentUserContext.Provider&gt;<br>  );<br>};</pre><p><em>(full file </em><a href="https://gist.github.com/mayyyc/9d29ff07674f35d091e8b36f460032cb"><em>here</em></a><em>)</em></p><p>In App.tsx, we wrap &lt;CurrentUserProvider /&gt; outside all the routes so it’s called before we render any components.</p><pre>&lt;ApolloProvider client={client}&gt;<br>                    &lt;CurrentUserProvider&gt;<br>                      &lt;Container&gt;<br>                        &lt;Router&gt;<br>                          &lt;Login path={LOGIN_PATH} /&gt;<br>                          &lt;Home path={HOME_PATH} /&gt;<br>                          &lt;Tasks path={TASKS_PATH} /&gt;<br>                          &lt;Opportunities path={OPPORTUNITIES_PATH} /&gt;<br>                          &lt;Close path={CLOSE_PATH} /&gt;<br>                        &lt;/Router&gt;<br>                      &lt;/Container&gt;<br>                    &lt;/CurrentUserProvider&gt;<br>                  &lt;/ApolloProvider&gt;</pre><p><em>(full file </em><a href="https://gist.github.com/mayyyc/5ed18900785ee6a617010199335d80a8"><em>here</em></a><em>)</em></p><p>When a user is redirected to the login page, we can’t let user log in within the add-in as that will require an API call which we don’t have on the backend, we want to reuse the web app login using session cookie which is already there.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*lnBn0_KbP1eYEGBUCvlN4g.png" /><figcaption>add-in login page</figcaption></figure><p>So the trick is, we have a button on the add-in login page. When you click on it, it opens up the web app in a dialog. And after the user logs in and the dialog is closed, we want to refresh the add-in.</p><p>In Login.tsx:</p><pre>export const Login: React.FC&lt;RouteComponentProps&gt; = ({}) =&gt; {<br>  const showLoginDialog = useCallback(() =&gt; {<br>    const display = () =&gt;<br>      new Promise&lt;string&gt;((resolve) =&gt; {<br>                <strong>displayDialogAsync</strong>(<br>          `${window.location.origin}/sessions/new?outlook_plugin=true`,<br>          {<br>            displayInIframe: false,<br>          },<br>          resolve<br>        );<br>      });</pre><pre>    const displayAsync = async () =&gt; {<br>      await display();<strong><br>      location.replace(HOME_PATH); //very important,</strong><br>    };</pre><pre>    return displayAsync();<br>  }, []);<br>  return (<br>    &lt;div className={classes.root}&gt;<br>      ...<br>      &lt;Button<br>        variant=&quot;contained&quot;<br>        color=&quot;primary&quot;<br>        size=&quot;small&quot;<br>        onClick={<strong>showLoginDialog</strong>}<br>        className={classes.login}<br>      &gt;<br>        Log in<br>      &lt;/Button&gt;<br>      ...<br>    &lt;/div&gt;<br>  );</pre><p>in displayDialogAsync.ts:</p><pre>export const displayDialogAsync = (<br>  startAddress: string,<br>  options: Office.DialogOptions,<br>  onSuccess?: (message: string) =&gt; void,<br>  onError?: (error: any) =&gt; void,<br>  onEnd?: () =&gt; void<br>) =&gt;<br>  Office.context.ui.displayDialogAsync(<br>    startAddress,<br>    options,<br>    (showDialogResult) =&gt; {<br>      /**<br>       * The following are errors resulting from the attempt to show the dialog.<br>       * A successful result will be emitted if the dialog was successfully displayed<br>       * and is now visible to the user.<br>       */<br>      if (showDialogResult.status == Office.AsyncResultStatus.Failed) {<br>        // In addition to general system errors, there are 3 specific errors for<br>        // displayDialogAsync that you can handle individually.<br>        switch (showDialogResult.error.code) {<br>          case 12004:<br>            console.log(&quot;Domain is not trusted&quot;);<br>            break;<br>          case 12005:<br>            console.log(&quot;HTTPS is required&quot;);<br>            break;<br>          case 12007:<br>            console.log(&quot;A dialog is already opened.&quot;);<br>            break;<br>          default:<br>            console.log(showDialogResult.error.message);<br>            onError &amp;&amp; onError(showDialogResult.error);<br>            break;<br>        }<br>      } else {<br>        const dialog = showDialogResult.value;</pre><pre><strong>const messageHandler = ({ message }: any) =&gt; {<br>          onSuccess &amp;&amp; onSuccess(message);<br>          dialog.close(); // notify the parent dialog is closed<br>          if (onEnd) onEnd();<br>        };</strong></pre><pre>const eventHandler = (arg: any) =&gt; {<br>          // In addition to general system errors, there are 2 specific errors<br>          // and one event that you can handle individually.<br>          switch (arg.error) {<br>            case 12002:<br>              console.error(&quot;Cannot load URL, no such page or bad URL syntax.&quot;);<br>              break;<br>            case 12003:<br>              console.error(&quot;HTTPS is required.&quot;);<br>              break;<br>            case 12006:<br>              // The dialog was closed, typically because the user the pressed X button.<br>              console.log(&quot;Dialog closed by user&quot;);<br>              break;<br>            default:<br>              console.error(&quot;Undefined error in dialog window&quot;);<br>              break;<br>          }<br>          if (onEnd) onEnd();<br>        };</pre><pre>/*Messages are sent by developers programatically from the dialog using office.context.ui.messageParent(...)*/<br>        <strong>dialog.addEventHandler(<br>          Office.EventType.DialogMessageReceived,<br>          messageHandler<br>        );</strong></pre><pre><strong>/*Events are sent by the platform in response to user actions or errors. For example, the dialog is closed via the &#39;x&#39; button*/<br>        dialog.addEventHandler(<br>          Office.EventType.DialogEventReceived,<br>          eventHandler<br>        );</strong><br>      }<br>    }<br>  );</pre><p>And the web app login handles the authentication and sets the session cookie.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rbVR7rcZqMvqqyN2OQ6WGA.png" /><figcaption>web app login</figcaption></figure><p>Once the user is logged in, we display a logged in page, which has a button which will send an event to Office API, and our displayDialogAsync function will resolve and the login page will then run location.replace and refresh the add-in and call the currentUser query again and this time, it will return data as the session cookie is set.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4bk1jGF2HAPixbttARATBQ.png" /><figcaption>logged in page</figcaption></figure><p>In LoggedIn.tsx:</p><pre>export const LoggedIn: React.FC&lt;RouteComponentProps&gt; = ({ }) =&gt; {<br>  const classes = useStyles({});<br>  return (<br>    &lt;div className={classes.root}&gt;<br>      ...<br>      &lt;Button<br>        variant=&quot;contained&quot;<br>        color=&quot;primary&quot;<br>        size=&quot;small&quot;<br><strong>        onClick={() =&gt; Office.context.ui.messageParent(&#39;true&#39;)}</strong><br>        className={classes.login}<br>      &gt;<br>        Start Exploring<br>      &lt;/Button&gt;<br>    &lt;/div&gt;<br>  );<br>};</pre><p>That’s our login flow using session cookie.</p><h3>Set up proxy for local development</h3><p>This flow brings an issue for our local development as add-in are a different server from the backend server(where the web app login is), we have to set up proxy so the add-in can have the session cookie from backend server. But this isn’t an issue on production server as the add-in will be compiled and hosted on the same server as the web app.</p><p>This might not be an issue for you depending how you app is set up, and you can follow this <a href="https://create-react-app.dev/docs/proxying-api-requests-in-development/#configuring-the-proxy-manually">create-react-app documentation</a> on how to set up proxy.</p><p>It looks roughly like this:</p><pre>//setupProxy.js</pre><pre>const { createProxyMiddleware } = require(&quot;http-proxy-middleware&quot;);</pre><pre>module.exports = function (app) {<br>  app.use(<br>    &quot;/sessions/new&quot;,<br>    createProxyMiddleware({<br>      target: &quot;<a href="http://localhost:4000/">http://localhost:4000</a>&quot;,<br>      changeOrigin: true,<br>    })<br>  );<br>  <br>  app.use(<br>    &quot;/auth/developer&quot;,<br>    createProxyMiddleware({<br>      target: &quot;<a href="http://localhost:4000/">http://localhost:4000</a>&quot;,<br>      changeOrigin: true,<br>    })<br>  );<br>}</pre><p>And if your add-in doesn’t get the cookie, it might be some security setting on your session cookie. Try go to application &gt;cookies and find your session cookie and untick the Secure option and change SameSite option from None to Lax manually.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tQUIgCrc1LlazTcLiWXmuA.png" /></figure><p>Hope this helps =)</p><p><strong>More posts on buiding Outlook add-in with React:</strong></p><ul><li><a href="https://medium.com/nexl-engineering/build-an-outlook-add-in-with-react-part-0-setting-up-the-project-ddbaef68349c"><em>Part 0. Setting up the project</em></a></li><li><a href="https://medium.com/nexl-engineering/building-an-outlook-add-in-with-react-part-1-getting-data-emails-contacts-from-office-api-bb48751d645b"><em>Part 1. Getting Mailbox Data from Office API</em></a></li><li><a href="https://medium.com/@mayyyyyyc/building-an-outlook-add-in-with-react-part-2-pinnable-task-pane-dc08411b5d55">Part 2. Pinnable Task Pane</a></li><li><a href="https://medium.com/@mayyyyyyc/part-3-open-link-from-a-ribbon-button-building-outlook-add-in-with-react-a49fc130810">Part 3. Open Link from a Ribbon Button</a></li><li><a href="https://medium.com/@mayyyyyyc/part-4-authentication-with-session-cookie-building-outlook-add-in-with-react-6d6561f8cc77">Part 4. Authentication with Session Cookie</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6d6561f8cc77" width="1" height="1" alt=""><hr><p><a href="https://medium.com/nexl-engineering/part-4-authentication-with-session-cookie-building-outlook-add-in-with-react-6d6561f8cc77">Part 4. Authentication with Session Cookie — Building Outlook Add-in with React</a> was originally published in <a href="https://medium.com/nexl-engineering">NEXL Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>