<?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 Liad Shiran on Medium]]></title>
        <description><![CDATA[Stories by Liad Shiran on Medium]]></description>
        <link>https://medium.com/@liadshiran92?source=rss-e3355a31518e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*anwFyuDVzYdb85Woue6O-g.jpeg</url>
            <title>Stories by Liad Shiran on Medium</title>
            <link>https://medium.com/@liadshiran92?source=rss-e3355a31518e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 16:44:19 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@liadshiran92/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[Alternative to window.prompt in React]]></title>
            <link>https://medium.com/@liadshiran92/alternative-to-window-prompt-in-react-a266448e1d2?source=rss-e3355a31518e------2</link>
            <guid isPermaLink="false">https://medium.com/p/a266448e1d2</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[prompt]]></category>
            <category><![CDATA[context]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[hooks]]></category>
            <dc:creator><![CDATA[Liad Shiran]]></dc:creator>
            <pubDate>Mon, 13 Jun 2022 12:03:59 GMT</pubDate>
            <atom:updated>2022-06-13T13:03:33.372Z</atom:updated>
            <content:encoded><![CDATA[<h4>Using Context, Hooks, and TypeScript</h4><p>In this post, I will go over my implementation of an alternative to window.alert , window.confirm andwindow.prompt using React. <br>All of the examples are written with TypeScript.<br>A demo with full source code is available at the end.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vfk7OVG-sWXMLGn1" /><figcaption>Photo by <a href="https://unsplash.com/@clemono?utm_source=medium&amp;utm_medium=referral">Clem Onojeghuo</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote><strong>window.alert</strong> - shows a message<br><strong>window.confirm</strong> - shows a message + returns true / false<br><strong>window.prompt</strong> - shows a message + returns a string user input</blockquote><h3>The Result</h3><p>Starting from the end, let’s see what we’re trying to achieve:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/261c4c9610b7f236867fd4d9093a58e1/href">https://medium.com/media/261c4c9610b7f236867fd4d9093a58e1/href</a></iframe><p>The above component is a Button with some behavior for onClick , with the caveat that we want to warn the user before actually running the callback named doAction. <br>This is somewhat similar to where we would use window.alert or window.confirm .</p><p>Let’s take a look at another example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/56ed5880041b9180c49045f4597bb5a6/href">https://medium.com/media/56ed5880041b9180c49045f4597bb5a6/href</a></iframe><p>In the second example, our Button component adds a new string item to a list in its state. The string is defined by user input.<br>This is somewhat similar to where we would use window.prompt .</p><h3>usePrompt</h3><p>Let’s have a look at how we implemented usePrompt , a shared custom hook, which we used before in the result examples:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0c068c5b77d1213501a5c22ee68b123a/href">https://medium.com/media/0c068c5b77d1213501a5c22ee68b123a/href</a></iframe><p>We can see that it’s just a simple hook that returns a triggerPrompt callback. The “magic” still lays inside PromptContext , which encapsulates a setPrompt function that receives isOpen and PromptProps .</p><h3>PromptContext</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/226e4b93dff34f852af525e22fe564a1/href">https://medium.com/media/226e4b93dff34f852af525e22fe564a1/href</a></iframe><p>This may seem long, but it’s primarily types and default props when looking closer.</p><p>The interesting part is at the bottom, where we create PromptContextProvider to wrap our app content. This makes PromptContext capable of holding a global prompt state for isOpen and props , which we can access from anywhere using the usePrompt hook from before.</p><p>The next thing to do is to wrap our app with PromptContextProvider like so:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5246d0c2b2338b9de89fe3f07a6f6987/href">https://medium.com/media/5246d0c2b2338b9de89fe3f07a6f6987/href</a></iframe><p>Lastly, we implement a custom Prompt component to our liking, using any kind of Modal component we prefer:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ea67ce65bad68f4999c51734e2b2111a/href">https://medium.com/media/ea67ce65bad68f4999c51734e2b2111a/href</a></iframe><p>And that’s it!</p><h3>Demo</h3><p>Let’s see everything in action:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Flxvlw7&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Flxvlw7&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Flxvlw7%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/a57d4039fc733350bf86af18e7434e7a/href">https://medium.com/media/a57d4039fc733350bf86af18e7434e7a/href</a></iframe><p>Demo in full screen: <br><a href="https://lxvlw7.csb.app/">https://lxvlw7.csb.app/</a></p><p>Full source code:<br><a href="https://github.com/Liadshiran/react-prompt-context">https://github.com/Liadshiran/react-prompt-context</a></p><h3>Summary</h3><p>I hope this tutorial was helpful for you with the use cases I covered. <br>And if not, it may hopefully have inspired you with ideas on how to leverage Context to make our lives as React developers easier and our code more generic and understandable.</p><p>Feel free to reach out on Twitter or LinkedIn:<br>@<a href="https://twitter.com/liad_shiran">liad_shiran</a><br><a href="https://www.linkedin.com/in/liad-shiran/">linkedin.com/in/liad-shiran/</a></p><p>Liad</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a266448e1d2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RTK Query Best Practices]]></title>
            <link>https://medium.com/@liadshiran92/rtk-query-best-practices-e0296d1679e6?source=rss-e3355a31518e------2</link>
            <guid isPermaLink="false">https://medium.com/p/e0296d1679e6</guid>
            <category><![CDATA[rtk-query]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[redux-toolkit]]></category>
            <dc:creator><![CDATA[Liad Shiran]]></dc:creator>
            <pubDate>Mon, 14 Feb 2022 21:00:06 GMT</pubDate>
            <atom:updated>2022-02-16T21:11:56.956Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>TLDR; In this post, I’ll address the main questions and concerns that fellow developers in my group brought up since we started using RTK Query in our newer apps.</blockquote><p>In June 2021, Redux Toolkit introduced a powerful tool for data fetching and caching called <a href="https://redux-toolkit.js.org/rtk-query/overview">RTK Query</a>.</p><p>Compared to popular alternatives like React-Query, the main strength of RTK Query is its default integration with the redux store. It generates actions that can be caught by other reducers, thunks, and even Redux DevTools, which is very convenient.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/668/1*B9HwKGiMI5J_i0UuOIsSHQ.jpeg" /><figcaption>RTK Query</figcaption></figure><h3>- What is the responsibility of RTK Query? 🤔</h3><p>RTK Query is responsible for:</p><ul><li>Fetching data and keeping cached data on the client-side.</li><li>Mutating data (create/update/delete) and syncing the changes from the server with the cache.</li><li>Keeping track of requests lifecycle (e.g isLoading, isError).</li><li>Serving cached data while avoiding duplicate requests for the same data.</li><li>Refetching data when necessary (and syncing with the cache).</li></ul><h3>- Should we use RTK Query for EVERY request? 🤔</h3><p>Ideally, yes. We should use the API object (RTK Query exports createApi) to query/mutate any exposed API endpoint that the app needs. There has to be one API slice per app for RTKQ to work best. For more info, check out: <a href="https://redux.js.org/tutorials/essentials/part-7-rtk-query-basics#defining-an-api-slice">Defining an API slice</a>.</p><p>To take full advantage of it, we can, and should, use RTKQ for all requests. Even for requests that are not directly serving UI components (via React hooks). For more info, check out: <a href="https://redux-toolkit.js.org/rtk-query/usage/usage-without-react-hooks">Usage Without React Hooks</a>.</p><h3>- Should we still use the good old redux store? 🤔</h3><p>It’s important to know that createApi is just an abstraction level over RTK’s createSlice(which in itself abstracts createReducer+createAction). <br>It generates another reducer to add to a redux store that may already have other reducers.</p><p>There may still be regular reducers in apps that fully leverage RTKQ (non createApi reducers). They can handle any global state that is not server data. For example, filter state, search term, toggle state, pagination state, etc.</p><p>For any server data caching in the client, we should only use RTKQ’s API slice reducer and refrain from holding server data elsewhere (otherwise, we will need to sync its state manually in case of updates/mutations).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B2OkpQS8xPNq08G4KPRBYg.png" /><figcaption>A redux store with RTKQ API reducer along with regular reducers</figcaption></figure><h3>- What about complex logic of multiple API calls? 🤔</h3><p>In most cases, we will need to execute one request followed by another or multiple requests in parallel.<br>For both of these cases, we should RTKQ’s <a href="https://redux-toolkit.js.org/rtk-query/api/createApi#onquerystarted">onQueryStarted</a>- an optional parameter for the endpoint of the first request. It gives us access to the original promise object of the request ( queryFulfilled) and we can either await it or use Promise.all with it along with other promises.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NSFxKr-VNctRlWigpzmD5g.png" /><figcaption>A complex request that fires multiple calls to the server</figcaption></figure><h3>- Do we still need async actions (e.g. thunks)? 🤔</h3><p>From my experience with RTKQ, <a href="https://redux-toolkit.js.org/rtk-query/api/createApi#onquerystarted">onQueryStarted</a> is very useful and can replace most of the redux async middleware in the application <br>(e.g. redux-thunk, redux-saga, redux-logic).</p><p>With that said, we might still need an async action if we don’t want our logic to depend on a single endpoint,<strong> </strong>and be more generic (e.g., bootstrapping a page with some requests).</p><p>It’s okay to use async actions alongside <a href="https://redux-toolkit.js.org/rtk-query/api/createApi#onquerystarted">onQueryStarted</a> logics<strong> </strong>if it seems necessary (Check out RTK’s <a href="https://redux-toolkit.js.org/api/createAsyncThunk">createAsyncThunk</a>).</p><h3>- How to refetch data / invalidate cache properly? 🤔</h3><p>The main method of refreshing data with RTKQ is using <a href="https://redux-toolkit.js.org/rtk-query/usage/automated-refetching#cache-tags">Cache Tags</a>. It’s most helpful when dealing with resources that have both query endpoints and mutation endpoints (e.g. GET /users and POST /users).</p><p>We can provide a tag to the query endpoint (a simple string tag or a more complex object tag), and all resources from this query endpoint will receive the tag. Once we call a mutation endpoint that is defined to invalidate this tag, all of the query endpoints that have this tag will automatically refetch and update the cache (the store).</p><p>In addition to cache tags, there are more methods for cache invalidation (for different use cases). In short:</p><ul><li>refetch : A function returned by the query hooks. Triggers a refetch (usually to be called inside useEffect).</li><li>initiate : A function on the endpoint object. Triggers a refetch.</li><li>keepUnusedDataFor : How long (seconds) to keep data with no subscribers (no rendered components that use it). The default value is 60.</li><li>refetchOnMountOrArgChange : Refetches more frequently - when new components subscribe, or a hook is called with different arguments.</li><li>refetchOnFocus : Refetch on window focus or tab switch.</li><li>refetchOnReconnect : Refetches if internet connection is re-established.</li><li><a href="https://redux-toolkit.js.org/rtk-query/usage/manual-cache-updates">updateQueryData</a> : A more advanced way to manually update the cache value for an endpoint, for cases when automated updates with Tags aren’t enough (e.g. update before the response arrives).</li></ul><p>More information about these can be found <a href="https://redux-toolkit.js.org/rtk-query/usage/cache-behavior">here</a>.</p><h3>- How to handle errors properly? 🤔</h3><p>The way we receive the error object depends on whether we use the default fetchBaseQuery (which returns a property called error) or we use a <a href="https://redux-toolkit.js.org/rtk-query/usage/customizing-queries">custom fetch query</a> (in which we can decide how to return the error).</p><p>In case we need a special treatment for an error of a specific endpoint, we can do it with onQueryStarted by catching the error on the queryFulfilled promise:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ywxXE5yVvtM13U_p0FpbBw.png" /><figcaption>catching the error of the promise inside onQueryStarted</figcaption></figure><h3>- How to create selectors that use RTKQ’s cached data? 🤔</h3><p>Each endpoint provides a select function that returns a selector for its cached data from the store (this selector may receive a cache key as an argument, which is the same argument we would call the query hooks with). We can create a simple selector like so:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/758/1*WAcOgSFt6R3N4lvl78Afyg.png" /><figcaption>creating a selector that serves cached data</figcaption></figure><blockquote>Note about the example: in cases where we may need multiple selectors for the same endpoint, it would be best to call api.endpoints.getUsers.select() separately and create multiple selectors that use it.</blockquote><p>This can also be useful for creating composed selectors or selectors that compute data (e.g with <a href="https://github.com/reduxjs/reselect">reslect</a>).</p><h3>- How to prevent hooks spam in “dumb” components? 🤔</h3><p>It’s true that RTKQ doesn’t help prevent components from being generic/dumb/presentational. It pushes us to connect more components directly to the store by supplying tons of React hooks.</p><p>But, this issue has nothing to do with RTKQ itself. <br>In my opinion, connecting more components to the store is not a bad practice and also improves performance. This is the direction that many React+Redux apps move toward nowadays in the hooks era, and RTKQ embraces this approach.</p><p><a href="https://medium.com/nmc-techblog/why-you-should-stop-using-the-container-presentational-pattern-in-redux-29b112406128">You can read more about this topic here.</a></p><p>If you are just concerned about how quickly we find ourselves using many hooks in one component (that uses multiple kinds of data/mutations), you can easily extract all of the hooks calls to a separate custom hook.</p><h3>Summary</h3><p>These are the best practices, in my opinion, for the most commonly asked questions I heard from my peers while introducing RTK Query. <br>I hope I have provided you with some helpful insights on the matter! 😃</p><p>Feel free to reach out for anything!<br><a href="https://twitter.com/liad_shiran">liad_shiran</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e0296d1679e6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Easy Drag and Drop in React]]></title>
            <link>https://medium.com/@liadshiran92/easy-drag-and-drop-in-react-22778b30ba37?source=rss-e3355a31518e------2</link>
            <guid isPermaLink="false">https://medium.com/p/22778b30ba37</guid>
            <category><![CDATA[drag-and-drop]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[open-source]]></category>
            <dc:creator><![CDATA[Liad Shiran]]></dc:creator>
            <pubDate>Wed, 18 Aug 2021 13:21:40 GMT</pubDate>
            <atom:updated>2021-08-18T13:28:31.577Z</atom:updated>
            <content:encoded><![CDATA[<h4>Using hooks and react-dnd</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ma8Rc-pzVXdPSu9uVZFa-Q.png" /></figure><h3>Intro</h3><p>In this post, I’ll explain the basics of the open-source library <a href="https://github.com/react-dnd/react-dnd">react-dnd</a> (version 14.0.2 as of now) and show some up-to-date code examples.</p><h3>Preparations</h3><ol><li>Install the libraries react-dnd and react-dnd-html5-backend using npm/yarn.</li><li>Wrap the container component (the one that renders components using drag-and-drop) with the DndProvider like so:</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d79224faa19f417106a1354fb05585f1/href">https://medium.com/media/d79224faa19f417106a1354fb05585f1/href</a></iframe><p>We need to supply react-dnd with a backend that encapsulates the actual use of the drag-and-drop API of the browser.<br>You will mostly only need <a href="https://react-dnd.github.io/react-dnd/docs/backends/html5">HTML5Backend</a> for starters, though it’s possible to use other drag-and-drop backends (like <a href="https://react-dnd.github.io/react-dnd/docs/backends/touch">touch</a> for mobile devices).</p><h3>Example #1 — Drag items into one drop area</h3><p>Almost everywhere I looked, the first example for implementing drag-and-drop was showing how to make many items draggable into one designated drop area.</p><p>Although this isn’t the requirement I had in mind, I quickly understood that this one is the most basic and easily explainable for DND newcomers. That’s why I felt it’s important to explain it here:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Obir7HMZ6_oM0e9miKmzoQ.gif" /></figure><h4>Drag</h4><p>This is the code for the PetCard component (the draggable item):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6db3de4d0e4b65166cf160ba406213fd/href">https://medium.com/media/6db3de4d0e4b65166cf160ba406213fd/href</a></iframe><p>Let’s go over this:</p><p>For any react element to be draggable, we need to give it a ref property which will be thedragRefreturned to us from the useDrag hook (that we imported from react-dnd). <br>This is the essential part of how we provide the library with the element that needs to be dragged.</p><p>useDrag receives an input object. The object must include a mandatory type property — a string that we define. This later becomes relevant when we create the drop area (to accept this type of draggable).</p><p>The next property is item . We use it to pass the data we will need later for the drop area. We only need the necessary data to render the representation of the item in the drop area (in this case, it’s the Petobject: id and name).</p><p>Next, we have an optional property called collect . This one is useful for many purposes. It is a function that receives a monitor object supplied to us by react-dnd , that holds the state and metadata of the drag action.<br>In our case, we use it to extract isDragging — a boolean that we can use to render a nice emoji in the card that is being dragged.<br>For the full monitor object API, I recommend checking out the <a href="https://react-dnd.github.io/react-dnd/docs/api/drag-source-monitor">documentation</a>.</p><h4>Drop</h4><p>This is the code for the Basket component (the drop area):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5532c819531091ce7a6c95751e93d7fa/href">https://medium.com/media/5532c819531091ce7a6c95751e93d7fa/href</a></iframe><p>First of all, we need React’s useState to save an array of items dropped in the drop area (the basket). We map each Pet object in the basket to a PetCard element to render inside the basket.</p><p>In addition, similar to before, to tell react-dnd that an element is a drop area, we need to supply it with a ref property. This time it’s dropRef , returned from the useDrop hook (in our example, it’s the second div we render at the bottom).</p><p>The useDrop hook receives an input object with a mandatory accept property, corresponding to the type property we passed to useDrag beforehand. The drop area will only react to a draggable of this type.</p><p>Then we have the drop property. It’s a callback function that triggers with every drop. It receives the data we passed in the item property for useDrag. In our example, we take the Pet data and add it to the basket array state (only if it’s not already there).<br>Notice that we don’t mutate the basket array. We return a new instance of it with the new Pet item added.</p><p>Finally, we have another collect function here, similar to the one we used before.<br>This time, we use it to extract isOver , a boolean that indicates whether the item being dragged is currently above (over) our drop area. With it, we render a “Drop Here” notice inside.</p><h3>Example #2 — Drag list items and change their order</h3><p>This example is a little more complex. But this time, it actually matches the requirement I had in mind when learning this library:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1004/1*hYHQYpn8Wesb4oPYRTSSyg.gif" /></figure><p>Notice how every list item is <strong>both</strong> draggable and a drop spot. This is crucial because it means every item component must implement both useDrag and useDrop hooks and combine them into one ref.</p><p>This is the code for ListItem , the white pet card in the example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8f7d718db843763cde61a45638133331/href">https://medium.com/media/8f7d718db843763cde61a45638133331/href</a></iframe><p>The props this component receive are:</p><ol><li>text — The text that the list item renders.</li><li>index — The index of the item in the list.</li><li>moveListItem — A callback to be executed when we need this item to move to another index (which happens when we hover past it like shown in the gif).</li></ol><p>For useDrag , we have basically the same input object as the first example, only that this time, the data that we pass on ( item property) is just the index.</p><p>The interesting part here is the input object we pass to useDrop . In particular- the hover function.</p><p>The hover function triggers every time a draggable hovers above this drop area. We use it in this example to move items up and down as the draggable hovers around the list items, always making some space to be dropped at.<br>The implementation may seem complex at first glance, but all it does is move the item up or down when the mouse exceeds the middle Y-axis of the item (as can be seen in the gif above).</p><p>Then, all that&#39;s left is to join the two refs into one and render the item as we please.</p><p>This is the code for List , the component that renders all the list items:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/44b1f4269262e66d04326ad4dfa2d1a0/href">https://medium.com/media/44b1f4269262e66d04326ad4dfa2d1a0/href</a></iframe><p>This is mostly just a container, and we don’t do any DND stuff here.</p><p>The only thing worth mentioning is the movePetListItem callback we pass into ListItem.<br> It receives two indexes and swaps the item’s position in the pets array from one to the other (from dragIndex to hoverIndex).</p><h3>More examples</h3><p>There are many more use cases for drag-and-drop that you may be interested in and I don’t talk about here.</p><p>You can find many more examples and implementations in the <a href="https://github.com/react-dnd/react-dnd">react-dnd</a> code and <a href="https://react-dnd.github.io/react-dnd/about">documentation</a><em>.</em></p><h3>Summary</h3><p>I decided to write this post after I’ve learned that the react-dnd library wasn’t as easy to use as I first expected.</p><p>I hope that with this post, I made it easier for you to start tinkering with this library yourselves.</p><p>Feel free to reach out to me for anything. I’m here on Medium and also on <br><a href="https://twitter.com/liad_shiran">Twitter</a>. I’d love to hear your feedback!</p><p>Stay safe!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=22778b30ba37" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Advanced console.log Tips & Tricks]]></title>
            <link>https://medium.com/@liadshiran92/advanced-console-log-tips-tricks-fa3762930bca?source=rss-e3355a31518e------2</link>
            <guid isPermaLink="false">https://medium.com/p/fa3762930bca</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[devtools]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Liad Shiran]]></dc:creator>
            <pubDate>Sat, 11 Apr 2020 20:32:22 GMT</pubDate>
            <atom:updated>2020-04-12T12:13:09.187Z</atom:updated>
            <content:encoded><![CDATA[<p>The console is the built-in debugger of the browser. Many developers use <strong><em>console.log()</em></strong> all the time to print messages and debug problems in their code. But this tool has a lot more to offer than you may have ever realized!</p><h3>Intro — The Console Object</h3><p>Let’s try something simple and run:</p><pre>console.log(console)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/809/1*brloat-YGFeiaNAzjUpBtA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/741/1*uyBF4ZdJDRCMj6L5xziJ7g.png" /></figure><p>As we can see, the console object has a lot more to offer than the good ol’ <strong><em>console.log()</em></strong><em> </em>function.</p><p>The truth is that there is probably a better way to log anything you need. All it takes is to know the alternative options you have and to get yourself used to them.</p><p>In this article, I’m going to introduce some of the more useful functionalities of the console object that I’ve adopted during my time as a web developer. After taking a look, you can judge for yourself if <strong><em>console.log()</em></strong> should remain your only go-to option for print debugging.</p><p>Let’s create a test object to use as an example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lsj7lmSaI6DlRWjw8LiVDg.png" /></figure><p>And that’s how it looks when we call <strong>console.log() </strong>with our object:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*4fvFgt9y52vgnb1zLvYQIA.png" /></figure><h3>console.dir()</h3><p>While <strong><em>console.log()</em></strong> prints the object in its string representation, <strong><em>console.dir()</em></strong> recognizes the object as an object and prints it’s properties in the form of a clean expandable list:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*Y7T_3dzqfQwcl7CXOHC1Eg.png" /></figure><h3>console.assert()</h3><p>With <strong><em>console.assert()</em></strong>, we can decide only to log something if a condition is <strong>false </strong>and save some console space by avoiding unnecessary message printing:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/1*EXXlH7RW4UWyS8W_fyuH8w.png" /></figure><h3>console.count()</h3><p>Instead of incrementing a counter manually, we can use <strong><em>console.count()</em></strong> to do the job for us! We can provide it with a label (“Pets” in this example), and the counter value will increment each time <strong><em>console.count(“Pets”) </em></strong>is called:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*TVV-ixioCja72qZqgiExlA.png" /></figure><h3>console.table()</h3><p>My personal favorite! Use <strong><em>console.table()</em></strong> to print a visually nice table representation of an object with labeled rows for each the objects’ properties:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wdDUTsFn-0DQH0JSX7lN7Q.png" /></figure><h3>console.time() / timeLog() / timeEnd()</h3><p>A popular one. Use <strong><em>console.time()</em></strong> to start a timer. Then, with each call to <strong><em>console.timeLog()</em></strong>, the time elapsed since the timer started will be printed.<br>When done, call<strong><em> console.timeEnd()</em></strong> to print the total amount of time:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*vKk4zEMN1oboEMDQDHimYw.png" /></figure><h3>console.trace()</h3><p>Another very useful one! When debugging deeply nested objects or functions, we may want to print the stack trace of the code. Call <strong><em>console.trace()</em></strong> from within the function you want at the top of the call stack, to see the exact places in the code that called it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/1*u42_mynBDcorZU2HDELoSA.png" /></figure><h3>console.group() / groupEnd()</h3><p>It’s possible to group messages to avoid spam and mess in the console, like so:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*3IVymLUCU83jHOYZvTmT2w.png" /></figure><p>Extra tip: use<strong><em> console.groupCollapsed() </em></strong>instead of <strong><em>console.group()</em></strong> and the group will be collapsed by default. This also makes things easier on the eyes.</p><h3>Bonus: CSS styling the console</h3><p>Just in case you want to flex your new godly logging abilities, use “%c” before a string and pass CSS styles as another argument:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bWUJJazlyxXQoBIrD_bmxw.png" /></figure><p>Now you can practically use the console to paint anything! 🎨</p><h3>Summary</h3><p>Sometimes we don’t realize we can make our lives as developers a little bit easier just by adapting new small habits, like being a console pro 😎.</p><p>I hope you find this information useful.<br>Happy debugging!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa3762930bca" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introducing the Nielsen Testing Style Guide]]></title>
            <link>https://medium.com/@liadshiran92/introducing-the-nielsen-testing-style-guide-5313024116c0?source=rss-e3355a31518e------2</link>
            <guid isPermaLink="false">https://medium.com/p/5313024116c0</guid>
            <category><![CDATA[jest]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-testing-library]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[testing]]></category>
            <dc:creator><![CDATA[Liad Shiran]]></dc:creator>
            <pubDate>Tue, 11 Feb 2020 07:03:48 GMT</pubDate>
            <atom:updated>2022-03-31T17:29:24.931Z</atom:updated>
            <content:encoded><![CDATA[<p>In the world of web development, testing our application is very important. Yet, there is a need for clear rules and standards for testing each part of our application correctly.</p><h3>👉 Intro</h3><p>Here in the Nielsen Tel-Aviv engineering team, we have multiple micro FrontEnd web applications. We utilize many tools (e.g., <em>React, Jest, Cypress, Enzyme, React-Testing-Library</em>, etc…) but we have always felt like writing frontend Javascript tests is just not standardized enough.</p><p>A few of us grouped and decided that we need a standard that defines how our tests should be written and organized.</p><p>We started to compare different testing patterns and best practices from the various development teams. We also searched the web for best practices. Eventually, we came up with the idea to write an open-source testing style guide! 💡</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/1*EIHPDJbR46zluYMLRDnrQQ.png" /><figcaption>GLaDOS focused on testing before it was cool</figcaption></figure><h3>📜 The Style Guide</h3><p>The Nielsen Testing Style Guide is the result of numerous sessions where we discussed many testing examples and ideas. We then put the polished conclusions of these discussions together in a document, with a matching explanation for each part and some code examples (<strong>DO</strong>s ✅ and <strong>DON’T</strong>s ❌).</p><p>We focused on FrontEnd testing, specifically using <em>Jest </em>and <em>React-Testing-Library</em> to test React/Redux applications but tried to come up with general guidelines as well.</p><p>In the style guide, we suggest using the AAA testing pattern (Arrange Act Assert), which we used in all of the code examples. We demonstrated our approaches for testing things like UI-Components, Asynchronous side-effects, react-hooks, redux, dates, and more.<br>Furthermore, we also addressed End-to-end tests and how we organize them into separate decoupled parts.</p><p>Check the style guide out on Github: <br><a href="https://github.com/nielsen-oss/docs/tree/master/javascript/testing"><strong><em>https://github.com/nielsen-oss/docs/tree/master/javascript/testing</em></strong></a></p><h3>🔍 Dive Into Details</h3><p>In this section, I will explore some of the main points you can take from the style guide.</p><h4>AAA — Arrange, Act, Assert</h4><p>We recommend structuring a test in a way that has visual separation between each part of the test:<br>1. <strong>Arrange</strong>- Preparations, mocks, rendering of components, etc.…<br>2. <strong>Act</strong>- Execution of the action under test.<br>3. <strong>Assert</strong>- Ensuring the expectation is satisfied. This part contains one test concept (while it may include more than one assertion).</p><h4>Implementation details testing vs. Behavioral testing</h4><p>While doing our research, we bumped into the concepts of <strong>implementation details</strong> testing and <strong>behavioral </strong>testing. These are two opposite approaches for UI-components unit tests.</p><p>Simply put, <strong>implementation details </strong>testing means making assertions about the inner implementation mechanisms of the component.<br>Common examples of this can be assertions about the inner component state or its internal functions. Also, calling internal functions during the test to imitate a particular behavior of the component, is considered implementation details testing (for example, calling the <em>onClick </em>handler function from the test).</p><p>On the other hand, <strong>behavioral</strong> testing means making assertions only about the result of an action, while imitating how the user interacts with the component.</p><p>After clarifying these two concepts, we all agreed that moving forward, behavioral<strong> testing </strong>is the correct way to go. That’s why we heavily recommend this testing approach in the style guide. We also recommend using <strong><em>react-testing-library</em> </strong>rather than <strong><em>enzyme</em></strong><em>.</em><strong><em><br></em></strong>The main reason is that <a href="https://testing-library.com/docs/react-testing-library/intro"><strong><em>react-testing-library</em></strong></a><strong><em> </em></strong>enforces writing behavioral tests, while <strong><em>enzyme</em></strong> allows wrong implementation details tests.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*20iuSJ8F0m9Td2MF4IKONg.png" /><figcaption>Tweet by Kent C. Dodds, the author of react-testing-library</figcaption></figure><p>Let’s take a look at some code examples:</p><p>❌ Implementation details test example (using <strong><em>enzyme</em></strong>):</p><pre><strong>test</strong>(‘shows the correct amount of clicks’, () =&gt; {<br>   const wrapper = <em>shallow</em>(&lt;Counter /&gt;)</pre><pre>wrapper.<em>find</em>(‘button’).<em>simulate</em>(‘click’)</pre><pre><em>expect</em>(wrapper.instance().state.count).to.<em>equal</em>(1)<br>})</pre><p>The above example is a <strong>bad</strong> test that relies on the implementation of the component. The <em>button</em> element may change to a <em>div </em>in the future. Also, accessing <em>wrapper.instance().state</em> is bad because it relies on the component being a <em>react class component</em> and that its <em>state</em> property has an attribute called “<em>count”.</em> These are all subjects to changes by developers that will unnecessarily break the test.</p><p>✅ Behavioral test example (using <strong><em>react-testing-library</em></strong>):</p><pre><strong>test</strong>(&#39;shows the correct amount of clicks&#39;, () =&gt; {<br>   const { getByText, <em>getByRole</em> } = <em>render</em>(&lt;Counter /&gt;)</pre><pre>fireEvent.<em>click</em>(getByText(&#39;increment&#39;))</pre><pre><em>expect</em>(<em>getByRole</em>(&#39;counter-value&#39;).textContent).<em>toBe</em>(&#39;1&#39;)<br>})</pre><p>The second example shows a <strong>good </strong>behavioral test. Clicking on an element that contains the text ‘increment’ and expecting the value of an element with the role ‘counter-value’ to be ‘1’, is exactly how the user interacts with the component. This test will <strong>not</strong> break after a change in the internal component implementation. It only tests the behavior of the component.</p><h4>End-to-end testing</h4><p>For End-to-end testing, we make use of the<strong> Page Object</strong> pattern, in which the test uses a designated object that represents a page of the application.</p><p>The page object and exposes methods to access and manipulate parts of the page. It encapsulates technical details of the page (like selectors).</p><p>We also introduce the concept of <strong>flows</strong>. A flow is a common reusable logic that you can use in multiple e2e tests. Flows may use one or more page objects to interact with the application. A good and frequent example of a flow can be <em>login-flow.</em></p><p>Page objects and flows are utilities that help us write better and organized tests. It’s important to notice that both page objects and flows don’t make assertions. There should be a clear and definitive responsibility to each of them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*kagXaDPBDPWDihwpz5KhKg.png" /></figure><p>The diagram above shows the relationship between each part of our E2E tests. In the actual style guide, we include some code snippets for each of the concepts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pNVzN12eCu0FSOeQ7UVrgg.jpeg" /></figure><h3>🎯 Summary</h3><p>In case you missed the link before, here it is again: <strong><br></strong><a href="https://github.com/nielsen-oss/docs/tree/master/javascript/testing"><strong><em>https://github.com/nielsen-oss/docs/tree/master/javascript/testing</em></strong></a></p><p>The style guide includes more exciting topics I didn’t write about in this post and goes even more into details and code examples.</p><p>We hope you find our style guide useful for your purposes!<br>Please feel free to use the style guide and even contribute to it (check the open issues).</p><p>We don’t expect everyone to agree with our approaches completely, so we encourage you to open issues, start discussions, or comment on one of the existing discussions.</p><p>Nevertheless, we believe that caring about the standards of our tests is a significant step in the process of writing better tests 💪</p><p><strong>Happy testing!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5313024116c0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>