<p>I wanted to get some more experience working with GraphQL mutations, so I worked on a new feature for my site that enabled a user to “like” a blog article. I ran into a little gotcha that is kind of obvious now that I know the solution but wasn’t obvious at the time.</p>
<p><video src="{asset:2490:url||//assets.trevor-davis.com/uploads/images/content/like-component.mp4}" autoplay="" loop="" muted="" controls="" playsinline></video></p>
<p>I didn’t think I needed to be fancy and store the “like” in the database and associate with the user, so I decided that tracking whether the user had liked the article in <code>localStorage</code> was enough and then keep track of the total article like count in the database. Seems easy enough right?</p>
<h2>The Problem</h2>
<p>This was my first approach in retrieving whether or not the user had liked the article from <code>localStorage</code>:</p>
<script src="https://gist.github.com/davist11/c5903d524119c16448dbb56e2ac65701.js"></script>
<p>And this is the error that I was getting:</p>
<pre>ReferenceError: window is not defined</pre>
<h2>The Fix</h2>
<p>At first I was &#x1f914;, but the fix is super simple and totally makes sense. Remix renders on the server, but I wanted to run this in the browser, so I simply needed to wrap it in a <code>useEffect</code>:</p>
<script src="https://gist.github.com/davist11/f1ac5d35cde425d875d477068203996e.js"></script>
<p>This is actually captured in the <a href="https://remix.run/docs/en/v1/guides/constraints#rendering-with-browser-only-apis">Remix docs</a>, but it was kind of buried.</p>