This is a valid RSS feed.
This feed is valid, but interoperability with the widest range of feed readers could be improved by implementing the following recommendations.
... ://www.peterbe.com/rss.xml" rel="self"/><language>en-us</language><lastB ...
^
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom"><channel><title> ...
<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom"><channel><title>Peterbe.com</title><link>http://www.peterbe.com/rss.xml</link><description>Stuff in Peter's head</description><atom:link href="http://www.peterbe.com/rss.xml" rel="self"/><language>en-us</language><lastBuildDate>Mon, 18 Nov 2024 16:20:15 +0000</lastBuildDate><item><title>An ideal pattern to combine react-router with tanstack/react-query</title><link>http://www.peterbe.com/plog/ideal-pattern-react-router-with-tanstackreact-query</link><description>If you use loaders in React Router and have them start XHR requests on the same QueryClient you use in your components, you can start API requests before you render the React page. This makes the page feel faster to load because you can have the back-end data ready for your eyes to feast on sooner.</description><pubDate>Mon, 18 Nov 2024 16:20:15 +0000</pubDate><guid>http://www.peterbe.com/plog/ideal-pattern-react-router-with-tanstackreact-query</guid></item><item><title>brotli_static in Nginx</title><link>http://www.peterbe.com/plog/brotli_static-in-nginx</link><description>`apt install libnginx-mod-http-brotli-static`</description><pubDate>Fri, 08 Nov 2024 17:06:28 +0000</pubDate><guid>http://www.peterbe.com/plog/brotli_static-in-nginx</guid></item><item><title>Object.keys to return the known strings of an object in TypeScript</title><link>http://www.peterbe.com/plog/object.keys-known-strings-object-ts</link><description>Use `keyof typeof myObject` to get the keys as an "list of strings" that are the keys of an object.</description><pubDate>Fri, 25 Oct 2024 13:07:32 +0000</pubDate><guid>http://www.peterbe.com/plog/object.keys-known-strings-object-ts</guid></item><item><title>How I make my Vite dev server experience faster</title><link>http://www.peterbe.com/plog/vite-dev-server-experience-faster</link><description>Use `server.warmup.clientFiles` to make Vite get to work on transforms as soon as possible, rather than on-demand. See what's going on using `vite --debug transform`</description><pubDate>Tue, 22 Oct 2024 14:14:10 +0000</pubDate><guid>http://www.peterbe.com/plog/vite-dev-server-experience-faster</guid></item><item><title>How to extend a function in TypeScript without repeating the signature types</title><link>http://www.peterbe.com/plog/extend-function-typescript-same-signature-types</link><description>Use the `Parameters<typeof someFunction>` to be able to extend or control the signature of a function you don't want to spell out.</description><pubDate>Wed, 16 Oct 2024 12:28:18 +0000</pubDate><guid>http://www.peterbe.com/plog/extend-function-typescript-same-signature-types</guid></item><item><title>Trying out the new Bun "Compile to bytecode"</title><link>http://www.peterbe.com/plog/trying-bun-compile-to-bytecode</link><description>Bun 1.1.30 added a `--bytecode` option to `bun build` and it does appear to make the executable faster</description><pubDate>Tue, 15 Oct 2024 11:49:16 +0000</pubDate><guid>http://www.peterbe.com/plog/trying-bun-compile-to-bytecode</guid></item><item><title>The performance benefits of code-split an SPA</title><link>http://www.peterbe.com/plog/performance-benefits-of-code-split-an-spa</link><description>Code-splitting can be great for web performance, but it's most likely about the underlying heavy libraries rather than your own code *using* those libraries.</description><pubDate>Sat, 12 Oct 2024 21:01:30 +0000</pubDate><guid>http://www.peterbe.com/plog/performance-benefits-of-code-split-an-spa</guid></item><item><title>Rate my golf swing (October 2024)</title><link>http://www.peterbe.com/plog/rate-my-golf-swing-october-2024</link><description>Video of my swing as of October 2024.</description><pubDate>Fri, 11 Oct 2024 20:10:35 +0000</pubDate><guid>http://www.peterbe.com/plog/rate-my-golf-swing-october-2024</guid></item><item><title>The 3 queries I use with pg_stat_statements to analyze slow PostgreSQL queries</title><link>http://www.peterbe.com/plog/3-queries-with-pg_stat_statements</link><description>3 primary SQL statements you need when using pg_stat_statements</description><pubDate>Mon, 30 Sep 2024 17:03:10 +0000</pubDate><guid>http://www.peterbe.com/plog/3-queries-with-pg_stat_statements</guid></item><item><title>How to handle success and failure in @tanstack/react-query useQuery hook</title><link>http://www.peterbe.com/plog/how-to-handle-success-and-failure-usequery-hook</link><description><p>What <a href="https://tanstack.com/query/latest/docs/framework/react/overview"><code>@tanstack/react-query</code> is</a> is a fancy way of fetching data, on the client, in a React app.</p>
<p>Simplified primer by example; instead of...</p>
<pre><code class="hljs">
<span class="hljs-keyword">function</span> <span class="hljs-title function_">MyComponent</span>(<span class="hljs-params"></span>) {
<span class="hljs-keyword">const</span> [userInfo, setUserInfo] = <span class="hljs-title function_">useState</span>(<span class="hljs-literal">null</span>)
<span class="hljs-title function_">useEffect</span>(<span class="hljs-function">() =&gt;</span> {
<span class="hljs-title function_">fetch</span>(<span class="hljs-string">&#x27;/api/user/info&#x27;</span>)
.<span class="hljs-title function_">then</span>(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> response.<span class="hljs-title function_">json</span>())
.<span class="hljs-title function_">then</span>(<span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> {
<span class="hljs-title function_">setUserInfo</span>(data)
})
}, [])
<span class="hljs-keyword">return</span> <span class="language-xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>Username: {userInfo ? userInfo.user_name : <span class="hljs-tag">&lt;<span class="hljs-name">em</span>&gt;</span>not yet known<span class="hljs-tag">&lt;/<span class="hljs-name">em</span>&gt;</span>}<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
}
</code></pre>
<!--split-->
<p>you now do this:</p>
<pre><code class="hljs">
<span class="hljs-keyword">import</span> { useQuery } <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;@tanstack/react-query&#x27;</span>
<span class="hljs-keyword">function</span> <span class="hljs-title function_">MyComponent</span>(<span class="hljs-params"></span>) {
<span class="hljs-keyword">const</span> {data} = <span class="hljs-title function_">useQuery</span>({
<span class="hljs-attr">queryKey</span>: [<span class="hljs-string">&#x27;userinfo&#x27;</span>],
<span class="hljs-attr">queryFn</span>: <span class="hljs-keyword">async</span> () {
<span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> <span class="hljs-title function_">fetch</span>(<span class="hljs-string">&#x27;/api/user/info&#x27;</span>)
<span class="hljs-keyword">return</span> response.<span class="hljs-title function_">json</span>()
}
})
<span class="hljs-keyword">return</span> <span class="language-xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>Username: {data ? data.user_name : <span class="hljs-tag">&lt;<span class="hljs-name">em</span>&gt;</span>not yet known<span class="hljs-tag">&lt;/<span class="hljs-name">em</span>&gt;</span>}<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
}
</code></pre>
<h2>That's a decent start, but...</h2>
<p>Error handling is a thing. Several things can go wrong:</p>
<ol>
<li>Complete network failure during the <code>fetch(...)</code> </li>
<li>Server being (temporarily) down </li>
<li>Not authorized </li>
<li>Backend URL not found </li>
<li>Backend URL found but wrong parameters</li>
</ol>
<p>None of the code solutions above deal with these things. At least not all of them.</p>
<p>By default, <code>useQuery</code> will retry if any error thrown inside that <code>queryFn</code> call.</p>
<blockquote>
<p><em>Queries that fail are silently </em><em>retried 3 times</em><em>, with exponential backoff delay before capturing and displaying an error to the UI.</em></p>
</blockquote>
<p>From the <a href="https://tanstack.com/query/latest/docs/framework/react/guides/important-defaults">documentation about important defaults</a></p>
<p>For example, if the server responds with a <code>403</code> the response body might not be of content-type JSON. So that <code>response.json()</code> might fail and throw and then <code>useQuery</code> will retry. You might be tempted to do this:</p>
<pre><code class="hljs">
queryFn: async () {
const response = await fetch(&quot;/api/user/info&quot;)
<span class="hljs-addition">+ if (!response.ok) {</span>
<span class="hljs-addition">+ throw new Error(`Fetching data failed with a ${response.status} from the server`)</span>
<span class="hljs-addition">+ }</span>
return response.json()
}
</code></pre>
<p>The problem with this is that <code>useQuery</code> still thinks it's an error and that it should retry. Sometimes it's the right thing to do, sometimes pointless.</p>
<h2>About retries</h2>
<p>The default implementation in @tanstack/react-query can be seen here: <a href="https://github.com/TanStack/query/blob/acb5d37f5c81753243978ff2f4b016c1009f3813/packages/query-core/src/retryer.ts#L164-L206"><code>packages/query-core/src/retryer.ts</code></a></p>
<p>In a gross simplification, it works like this:</p>
<pre><code class="hljs">
<span class="hljs-keyword">function</span> <span class="hljs-title function_">run</span>(<span class="hljs-params"></span>) {
<span class="hljs-keyword">const</span> promise = config.<span class="hljs-title function_">fn</span>()
<span class="hljs-title class_">Promise</span>.<span class="hljs-title function_">resolve</span>(promise)
.<span class="hljs-title function_">then</span>(resolve)
.<span class="hljs-title function_">catch</span>(<span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> {
<span class="hljs-keyword">if</span> (<span class="hljs-title function_">shouldRetry</span>(config)) {
<span class="hljs-keyword">await</span> <span class="hljs-title function_">sleep</span>(config.<span class="hljs-title function_">sleepTime</span>())
<span class="hljs-title function_">run</span>()
} <span class="hljs-keyword">else</span> {
<span class="hljs-title function_">reject</span>(error)
}
})
</code></pre>
<p>I'm not being accurate here but the point is that it's quite simple. The config has stuff like a count of how many times it's retried previously, dynamically whether it should retry, and how long it should sleep.<br />
The point is that it <strong>doesn't care what the nature of the error was</strong>. It doesn't test if the error was of type <code>Response</code> or if <code>error.message === "ECONNRESET"</code> or something like that.</p>
<p>So in a sense, it's a "dumping ground" for any error thrown. So if you look into the response, within your query function, and don't like the response, if you throw a new error, it will retry. And that might not be smart.</p>
<p>In simple terms; you <strong><em>should retry</em> if retrying is likely to yield a different result</strong>. For example, if the server responded with a <code>503 Service Unavailable</code> it's quite possible that if you just try again, a little later, it'll work.</p>
<p>What is wrong is if you get something like a <code>400 Bad Request</code> response. Then, trying again won't work.<br />
Another thing that is wrong is if your own code throws an error within. For example, ...</p>
<pre><code class="hljs">
<span class="hljs-attr">queryFn</span>: <span class="hljs-keyword">async</span> () {
<span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> <span class="hljs-title function_">fetch</span>(<span class="hljs-string">&#x27;/api/user/info&#x27;</span>)
<span class="hljs-keyword">const</span> userInfo = response.<span class="hljs-title function_">json</span>()
<span class="hljs-keyword">await</span> <span class="hljs-title function_">doSomethingComplexThatMightFail</span>(userInfo)
<span class="hljs-keyword">return</span> userInfo
}
</code></pre>
<h2>So, what's the harm?</h2>
<p>Suppose that you have something basic like this:</p>
<pre><code class="hljs">
<span class="hljs-attr">queryFn</span>: <span class="hljs-keyword">async</span> () {
<span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> <span class="hljs-title function_">fetch</span>(<span class="hljs-string">&quot;/api/user/info&quot;</span>)
<span class="hljs-keyword">if</span> (!response.<span class="hljs-property">ok</span>) {
<span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">`Fetching data failed with a <span class="hljs-subst">${response.status}</span> from the server`</span>)
}
<span class="hljs-keyword">return</span> response.<span class="hljs-title function_">json</span>()
}
</code></pre>
<p>and you use it like this:</p>
<pre><code class="hljs">
<span class="hljs-keyword">function</span> <span class="hljs-title function_">MyComponent</span>(<span class="hljs-params"></span>) {
<span class="hljs-keyword">const</span> {data, error} = <span class="hljs-title function_">useQuery</span>(...)
<span class="hljs-keyword">if</span> (error) {
<span class="hljs-keyword">return</span> <span class="language-xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>An error happened. Reload the page mayhaps?<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
}
<span class="hljs-keyword">if</span> (!data) {
<span class="hljs-keyword">return</span> <span class="language-xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>Loading...<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
}
<span class="hljs-keyword">return</span> <span class="language-xml"><span class="hljs-tag">&lt;<span class="hljs-name">AboutUser</span> <span class="hljs-attr">info</span>=<span class="hljs-string">{data.userInfo}/</span>&gt;</span></span>
}
</code></pre>
<p>then, I guess if it's fine to <em>not</em> be particularly "refined" about the error itself. It failed, refreshing the page might just work.</p>
<h2>If not an error, then what?</h2>
<p>The pattern I prefer, is to, if there is a problem with the response, to return it keyed as an error. Let's use TypeScript this time:</p>
<pre><code class="hljs">
<span class="hljs-comment">// THIS IS THE NAIVE APPROACH</span>
<span class="hljs-keyword">type</span> <span class="hljs-title class_">ServerResponse</span> = {
<span class="hljs-attr">user</span>: {
<span class="hljs-attr">first_name</span>: <span class="hljs-built_in">string</span>
<span class="hljs-attr">last_name</span>: <span class="hljs-built_in">string</span>
}
}
...
<span class="hljs-keyword">function</span> <span class="hljs-title function_">MyComponent</span>(<span class="hljs-params"></span>) {
<span class="hljs-keyword">const</span> {data, error, isPending} = <span class="hljs-title function_">useQuery</span>({
<span class="hljs-attr">queryKey</span>: [<span class="hljs-string">&#x27;userinfo&#x27;</span>],
<span class="hljs-attr">queryFn</span>: <span class="hljs-keyword">async</span> () {
<span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> <span class="hljs-title function_">fetch</span>(<span class="hljs-string">&#x27;/api/user/info&#x27;</span>)
<span class="hljs-keyword">if</span> (!response.<span class="hljs-property">ok</span>) {
<span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">`Bad response <span class="hljs-subst">${response.status}</span>`</span>)
}
<span class="hljs-keyword">const</span> user = <span class="hljs-keyword">await</span> response.<span class="hljs-title function_">json</span>()
<span class="hljs-keyword">return</span> user
}
})
<span class="hljs-keyword">return</span> <span class="language-xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>Username: {userInfo ? userInfo.user_name : <span class="hljs-tag">&lt;<span class="hljs-name">em</span>&gt;</span>not yet known<span class="hljs-tag">&lt;/<span class="hljs-name">em</span>&gt;</span>}<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
}
</code></pre>
<p>A better approach is to allow <code>queryFn</code> to return what it would 99% of the time, but also return an error, like this:</p>
<pre><code class="hljs">
<span class="hljs-comment">// THIS IS THE MORE REFINED APPROACH</span>
<span class="hljs-keyword">type</span> <span class="hljs-title class_">ServerResponse</span> = {
user?: {
<span class="hljs-attr">first_name</span>: <span class="hljs-built_in">string</span>
<span class="hljs-attr">last_name</span>: <span class="hljs-built_in">string</span>
}
errorCode?: <span class="hljs-built_in">number</span>
}
...
<span class="hljs-keyword">function</span> <span class="hljs-title function_">MyComponent</span>(<span class="hljs-params"></span>) {
<span class="hljs-keyword">const</span> {data, error, isPending} = <span class="hljs-title function_">useQuery</span>({
<span class="hljs-attr">queryKey</span>: [<span class="hljs-string">&#x27;userinfo&#x27;</span>],
<span class="hljs-attr">queryFn</span>: <span class="hljs-keyword">async</span> () {
<span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> <span class="hljs-title function_">fetch</span>(<span class="hljs-string">&#x27;/api/user/info&#x27;</span>)
<span class="hljs-keyword">if</span> (response.<span class="hljs-property">status</span> &gt;= <span class="hljs-number">500</span>) {
<span class="hljs-comment">// This will trigger useQuery to retry</span>
<span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">`Bad response <span class="hljs-subst">${response.status}</span>`</span>)
}
<span class="hljs-keyword">if</span> (response.<span class="hljs-property">status</span> &gt;= <span class="hljs-number">400</span>) {
<span class="hljs-keyword">return</span> {<span class="hljs-attr">errorCode</span>: response.<span class="hljs-property">status</span>}
}
<span class="hljs-keyword">const</span> user = <span class="hljs-keyword">await</span> response.<span class="hljs-title function_">json</span>()
<span class="hljs-keyword">return</span> {user}
}
})
<span class="hljs-keyword">if</span> (errorCode) {
<span class="hljs-keyword">if</span> (errorCode === <span class="hljs-number">403</span>) {
<span class="hljs-keyword">return</span> <span class="language-xml"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>You&#x27;re not authorized. <span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">&quot;/login&quot;</span>&gt;</span>Log in here<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span></span>
}
<span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">`Unexpected response from the API (<span class="hljs-subst">${errorCode}</span>)`</span>)
}
<span class="hljs-keyword">return</span> <span class="language-xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
Username: {userInfo ? userInfo.user_name : <span class="hljs-tag">&lt;<span class="hljs-name">em</span>&gt;</span>not yet known<span class="hljs-tag">&lt;/<span class="hljs-name">em</span>&gt;</span>}
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
}
</code></pre>
<p>It's just an example, but the point is; that you treat "problems" as valid results. That way you avoid throwing errors inside the query function, which will trigger nice retries.<br />
And in this example, it can potentially throw an error in the rendering phase, outside the hook, which means it needs your attention (and does not deserve a retry)</p>
<p>What's <strong>counter-intuitive</strong> about this is that your backend probably doesn't return the error optionally with the data. Your backend probably looks like this:</p>
<pre><code class="hljs">
<span class="hljs-comment"># Example, Python, backend JSON endpoint </span>
<span class="hljs-keyword">def</span> <span class="hljs-title function_">user_info_view</span>(<span class="hljs-params">request</span>):
<span class="hljs-keyword">return</span> JsonResponse({
<span class="hljs-string">&quot;first_name&quot;</span>: request.user.first,
<span class="hljs-string">&quot;last_name&quot;</span>: request.user.last
})
</code></pre>
<p>So, if that's how the backend responds, it'd be tempting to <em>model</em> the data fetched to that exact shape, but as per my example, you re-wrap it under a new key.</p>
<h2>Conclusion</h2>
<p>The shape of the data ultimately coming from within a <code>useQuery</code> function doesn't have to map one-to-one to how the server sends it. The advantage is that what you get back into the rendering process of your component is that there's a chance of capturing other types of errors that aren't retriable.</p></description><pubDate>Mon, 16 Sep 2024 10:27:38 +0000</pubDate><guid>http://www.peterbe.com/plog/how-to-handle-success-and-failure-usequery-hook</guid></item></channel></rss>
If you would like to create a banner that links to this page (i.e. this validation result), do the following:
Download the "valid RSS" banner.
Upload the image to your own server. (This step is important. Please do not link directly to the image on this server.)
Add this HTML to your page (change the image src
attribute if necessary):
If you would like to create a text link instead, here is the URL you can use:
http://www.feedvalidator.org/check.cgi?url=https%3A//www.peterbe.com/rss.xml