<?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 Scott Hu on Medium]]></title>
        <description><![CDATA[Stories by Scott Hu on Medium]]></description>
        <link>https://medium.com/@huzhen555?source=rss-9ff345d9fb22------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dKpD9NsszfUCT7vrNg5aIg.jpeg</url>
            <title>Stories by Scott Hu on Medium</title>
            <link>https://medium.com/@huzhen555?source=rss-9ff345d9fb22------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 22:51:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@huzhen555/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[I replaced TanStack Query with alova and cut my code by 70%]]></title>
            <link>https://medium.com/@huzhen555/i-replaced-tanstack-query-with-alova-and-cut-my-code-by-70-d6ec920502c2?source=rss-9ff345d9fb22------2</link>
            <guid isPermaLink="false">https://medium.com/p/d6ec920502c2</guid>
            <dc:creator><![CDATA[Scott Hu]]></dc:creator>
            <pubDate>Fri, 29 May 2026 08:45:46 GMT</pubDate>
            <atom:updated>2026-05-29T08:45:46.851Z</atom:updated>
            <content:encoded><![CDATA[<p>A frontend engineer’s real-world migration story â 5 scenarios, 133 lines reduced to 10.</p><p>Six months ago, I took on a mid-office project whose requirements spanned paginated lists, multi-step forms, real-time notifications via SSE, file uploads, and autocomplete search.</p><p>My initial choice was TanStack Query (formerly React Query). It’s the industry standard for data fetching in React, after all.</p><p>However, as the project expanded, I found myself wrapping TanStack Query in increasing layers of custom logic:</p><p>Pagination required useInfiniteQuery with manual page state management and data flattening via flatMap.</p><p>Forms needed separate state management and localStorage persistence on top of useMutation.</p><p>SSE had no native support, requiring a third-party library for connection management and reconnection logic.</p><p>Server-side retry was out of scope entirely â TanStack Query is client-only.</p><p>By project completion, I had accumulated over 2,000 lines of request-related code.</p><p>Then a colleague shared a link: alova.</p><p>— -</p><p>The first revelation: 50-line pagination â 3 lines</p><p>Before: TanStack Query pagination</p><p>// ~50 lines with useInfiniteQuery, manual page state, flatMap…</p><p>After: alova usePagination</p><p>import { usePagination } from ‘alova/client’</p><p>function TodoList() {<br> const {<br> loading, data, page,<br> pageSize, total,<br> nextPage, prevPage,<br> } = usePagination(<br> (page) =&gt; alova.Get(‘/api/todos’, { params: { page, pageSize: 10 } }),<br> { total: res =&gt; res.total }<br> )</p><p>if (loading) return &lt;Loading /&gt;</p><p>return (<br> &lt;div&gt;<br> {data.map(todo =&gt; &lt;TodoItem key={todo.id} todo={todo} /&gt;)}<br> &lt;Pagination<br> page={page} total={total}<br> onNext={nextPage} onPrev={prevPage}<br> /&gt;<br> &lt;/div&gt;<br> )<br>}</p><p>Three lines of core logic. Page state, size, total count, navigation controls, and loading states are all handled internally.</p><p>— -</p><p>Five scenarios compared</p><p>1. Form submission with draft persistence</p><p>TanStack Query’s useMutation handles submission only. Form state management, localStorage synchronization, and draft restoration must be implemented manually.</p><p>alova’s useForm with the store: true flag handles all of this automatically:</p><p>const {<br> form, loading, sendForm,<br> updateForm, reset,<br>} = useForm((formData) =&gt; alova.Post(‘/api/submit’, formData), {<br> initialForm: {},<br> store: true,<br>})<br>const handleSubmit = () =&gt; sendForm()</p><p>2. SSE real-time notifications</p><p>TanStack Query lacks built-in SSE support, requiring third-party libraries for stream connection and reconnection logic.</p><p>alova provides native useSSE with automatic connection state tracking via readyState.</p><p>3. Polling with focus refetch</p><p>Both libraries support polling. alova’s throttle parameter, however, applies consistently across both polling and focus refetch, preventing excessive requests during rapid tab switching.</p><p>4. Server-side retry and rate limiting</p><p>This is a key differentiator. TanStack Query’s retry mechanism is browser-only; it cannot operate in server environments.</p><p>alova’s retry and RateLimiter work natively in Node.js, Bun, and Deno. The RateLimiter can integrate with Redis for distributed rate limiting across processes â a capability critical for BFF layers and microservice architectures.</p><p>import { retry, RateLimiter } from ‘alova/server’</p><p>const result = await retry(<br> alovaInstance.Post(‘/api/order’, orderData),<br> { retry: 3, backoff: { start: 1000, multiplier: 2 } }<br>).send()</p><p>const limiter = new RateLimiter({<br> points: 10,<br> duration: 1,<br>})<br>const result = await limiter.limit(<br> alovaInstance.Get(‘/api/external’)<br>).send()</p><p>5. Cross-framework consistency</p><p>TanStack Query exposes different APIs for React, Vue, and Svelte. alova maintains a single API surface across React, Vue, Svelte, mini-programs, and Node.js â the same mental model applies everywhere.</p><p>— -</p><p>Quantified comparison</p><p>Scenario | TanStack Query | alova | Reduction<br>Paginated list | ~50 LOC | 3 LOC | 94%<br>Form + draft | ~35 LOC | 3 LOC | 91%<br>SSE notifications | ~30 LOC | 1 LOC | 97%<br>Auto-polling | ~10 LOC | 2 LOC | 80%<br>Server retry | ~8 LOC | 1 LOC | 87%<br>Total | ~133 LOC | ~10 LOC | 92.5%</p><p>When to choose which?</p><p>Simple CRUD with caching: TanStack Query remains an excellent choice.</p><p>Complex applications with diverse request patterns: alova’s strategy-based approach reduces boilerplate significantly.</p><p>Cross-framework or cross-platform projects: alova’s uniform API is a clear advantage.</p><p>Server-side request control: alova is the only option with built-in retry, rate limiting, and distributed locking.</p><p>— -</p><p>GitHub: alovajs/alova (<a href="https://github.com/alovajs/alova">https://github.com/alovajs/alova</a>)<br>Documentation: alova.js.org (<a href="https://alova.js.org/en/">https://alova.js.org/en/</a>)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d6ec920502c2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Client to Server: Alova 3’s Full-Stack Request Strategy Practice]]></title>
            <link>https://medium.com/@huzhen555/from-client-to-server-alova-3s-full-stack-request-strategy-practice-808a53b652e7?source=rss-9ff345d9fb22------2</link>
            <guid isPermaLink="false">https://medium.com/p/808a53b652e7</guid>
            <category><![CDATA[deno]]></category>
            <category><![CDATA[axios]]></category>
            <category><![CDATA[https]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Scott Hu]]></dc:creator>
            <pubDate>Thu, 04 Dec 2025 14:52:10 GMT</pubDate>
            <atom:updated>2025-12-04T14:52:10.021Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EfLUjzDRxKngrhRQBnH-ww.jpeg" /></figure><p>Many people may still think of alova as a lightweight request strategy library, which is certainly the core feature of alova 2. For example, consider the following code:</p><pre>const { loading, data, error } = useRequest(() =&gt; alovaInstance.Get(&#39;/xxx&#39;))</pre><p>This is a typical example of alova being used on the client side. However, alova has now been updated to version 3. Of course, these client strategies remain intact, but it’s no longer limited to the client side — it can now handle server-side scenarios with ease.</p><p>Alova 3 provides server-side request strategies (server hooks) and server-side storage adapters like Redis and file storage, allowing us to conveniently implement full-chain requests and forwarding on the server side.</p><p>Let’s first look at the complete flow of a request:</p><pre>Client (Browser/App)<br>    → Node.js BFF Layer (data transformation, etc.)<br>    → API Gateway (authentication, rate limiting, routing, etc.)<br>    → Backend Microservices</pre><p>The server hooks and distributed multi-level caching provided by alova allow us to easily implement request handling at all of the above levels.</p><h3>Forwarding Client Requests in the BFF Layer</h3><p>In the BFF layer, we often need to forward client requests to backend microservices. You can use async_hooks to access the context of each request and add it to the request in alova&#39;s beforeRequest, enabling the forwarding of user-related data.</p><pre>import { createAlova } from &#39;alova&#39;;<br>import adapterFetch from &#39;@alova/fetch&#39;;<br>import express from &#39;express&#39;;<br>import { AsyncLocalStorage } from &#39;node:async_hooks&#39;;<br><br>// Create async local storage instance<br>const asyncLocalStorage = new AsyncLocalStorage();<br>const alovaInstance = createAlova({<br>  requestAdapter: adapterFetch(),<br>  beforeRequest(method) {<br>    // Get request headers from async context and pass to downstream<br>    const context = asyncLocalStorage.getStore();<br>    if (context &amp;&amp; context.headers) {<br>      method.config.headers = {<br>        ...method.config.headers,<br>        ...context.headers<br>      };<br>    }<br>  },<br>  responded: {<br>    onSuccess(response) {<br>      // Data transformation processing<br>      return {<br>        data: response.data,<br>        timestamp: Date.now(),<br>        transformed: true<br>      };<br>    },<br>    onError(error) {<br>      console.error(&#39;Request failed:&#39;, error);<br>      throw error;<br>    }<br>  }<br>});<br>const app = express();<br>// Set once in middleware, automatically passed throughout<br>app.use((req, res, next) =&gt; {<br>  const context = {<br>    userId: req.headers[&#39;x-user-id&#39;],<br>    token: req.headers[&#39;authorization&#39;]<br>  };<br>  asyncLocalStorage.run(context, next);<br>});<br>// Business code focuses on business logic<br>app.get(&#39;/api/user-profile&#39;, async (req, res) =&gt; {<br>  // No need to manually pass context anymore!<br>  const [userInfo, orders] = await Promise.all([<br>    alovaInstance.Get(&#39;http://gateway.com/user/profile&#39;),<br>    alovaInstance.Get(&#39;http://gateway.com/order/recent&#39;)<br>  ]);<br>  res.json({ user: userInfo.data, orders: orders.data });<br>});</pre><h3>Use Cases in API Gateway</h3><p>In gateways, authentication, request rate limiting, and request distribution are often needed. Alova 3’s Redis storage adapter and rateLimiter can effectively implement distributed authentication services and request rate limiting.</p><h3>Authentication Can Be Done Like This</h3><p>If authentication tokens have an expiration time, you can configure a Redis storage adapter in the gateway to store tokens in Redis for reuse. For single-machine cluster services, you can also use the <a href="https://alova.js.org/resource/storage-adapter/file">@alova/storage-file</a> file storage adapter.</p><pre>import { createAlova } from &#39;alova&#39;;<br>import RedisStorageAdapter from &#39;@alova/storage-redis&#39;;<br>import adapterFetch from &#39;@alova/fetch&#39;;<br>import express from &#39;express&#39;;<br><br>const redisAdapter = new RedisStorageAdapter({<br>  host: &#39;localhost&#39;,<br>  port: &#39;6379&#39;,<br>  username: &#39;default&#39;,<br>  password: &#39;my-top-secret&#39;,<br>  db: 0<br>});<br>const gatewayAlova = createAlova({<br>  requestAdapter: adapterFetch(),<br>  async beforeRequest(method) {<br>    const newToken = await authRequest(method.config.headers[&#39;Authorization&#39;], method.config.headers[&#39;UserId&#39;])<br>    method.config.headers[&#39;Authorization&#39;] = `Bearer ${newToken}`;<br>  }<br>  // Set L2 storage adapter<br>  l2Cache: redisAdapter,<br>  // ...<br>});<br>const authRequest = (token, userId) =&gt; gatewayAlova.Post(&#39;http://auth.com/auth/token&#39;, null, {<br>  // Set 3-hour cache, will be saved in Redis, subsequent requests with same parameters will hit cache<br>  cacheFor: {<br>    mode: &#39;restore&#39;,<br>    expire: 3 * 3600 * 1000<br>  },<br>  headers: {<br>    &#39;x-user-id&#39;: userId,<br>    &#39;Authorization&#39;: `Bearer ${token}`<br>  }<br>});<br>const app = express();<br>// Implement app to receive all requests and forward to alova<br>// Register routes for all HTTP methods<br>const methods = [&#39;get&#39;, &#39;post&#39;, &#39;put&#39;, &#39;delete&#39;, &#39;patch&#39;, &#39;options&#39;, &#39;head&#39;];<br>methods.forEach(method =&gt; {<br>  app[method](&#39;*&#39;, async (req, res) =&gt; {<br>    const { method, originalUrl, headers, body, query } = req;<br>    // Use alova to send request<br>    const response = await gatewayAlova.Request({<br>      method: method.toLowerCase(),<br>      url: originalUrl,<br>      params: query,<br>      data: body,<br>      headers<br>    });<br>    // Forward response headers<br>    for (const [key, value] of response.headers.entries()) {<br>      res.setHeader(key, value);<br>    }<br>    // Send response data<br>    res.status(response.status).send(await response.json());<br>  });<br>});<br>app.listen(3000, () =&gt; {<br>  console.log(&#39;Gateway server started on port 3000&#39;);<br>});</pre><p>Of course, if you need to re-authenticate for every request, you can also remove cacheFor in authRequest to disable caching.</p><h3>Rate Limiting Strategy</h3><p>Alova’s rateLimiter can implement distributed rate limiting strategies, internally using node-rate-limiter-flexible. Let&#39;s refactor the implementation:</p><pre>import { createRateLimiter } from &#39;alova/server&#39;;<br>const rateLimit = createRateLimiter({<br>  /**<br>   * Time for points reset, in ms<br>   * @default 4000<br>   */<br>  duration: 60 * 1000,<br>  /**<br>   * Maximum consumable quantity within duration<br>   * @default 4<br>   */<br>  points: 4,<br>  /**<br>   * Namespace, prevents conflicts when multiple rateLimits use the same storage<br>   */<br>  keyPrefix: &#39;user-rate-limit&#39;,<br>  /**<br>   * Lock duration in ms, indicates that when rate limit is reached, it will extend [blockDuration]ms, e.g., 5 wrong passwords in 1 hour locks for 24 hours, this 24 hours is this parameter<br>   */<br>  blockDuration: 24 * 60 * 60 * 1000<br>});<br>const methods = [&#39;get&#39;, &#39;post&#39;, &#39;put&#39;, &#39;delete&#39;, &#39;patch&#39;, &#39;options&#39;, &#39;head&#39;];<br>methods.forEach(method =&gt; {<br>  app[method](&#39;*&#39;, async (req, res) =&gt; {<br>    const { method, originalUrl, headers, body, query } = req;<br>    // Use rateLimit wrapper here, it will use l2Cache storage adapter by default to store control parameters, in this example it will use Redis storage adapter.<br>    const method = gatewayAlova.Request({<br>      method: method.toLowerCase(),<br>      url: originalUrl,<br>      params: query,<br>      data: body,<br>      headers<br>    });<br>    const response = await rateLimit(method, {<br>      key: req.ip // Use IP as tracking key to prevent frequent requests from the same IP<br>    });<br>    // ...<br>  });<br>});</pre><h3>Third-Party Service Integration: Automatic Token Maintenance</h3><p>Integrating with external APIs requires access_token management, and many third-party access_tokens have usage limits. Here we can use alova 3 + Redis storage adapter to implement distributed automatic lifecycle maintenance of access_tokens, where Redis is used for access_token caching, and atom hook is used for atomic operations of distributed token updates.</p><pre>import { createAlova, queryCache } from &#39;alova&#39;;<br>import RedisStorageAdapter from &#39;@alova/storage-redis&#39;;<br>import adapterFetch from &#39;@alova/fetch&#39;;<br>import { atomize } from &#39;alova/server&#39;;<br><br>const redisAdapter = new RedisStorageAdapter({<br>  host: &#39;localhost&#39;,<br>  port: &#39;6379&#39;,<br>  username: &#39;default&#39;,<br>  password: &#39;my-top-secret&#39;,<br>  db: 0<br>});<br>const thirdPartyAlova = createAlova({<br>  requestAdapter: adapterFetch(),<br>  async beforeRequest(method) {<br>    // Check if it&#39;s a third-party API, if so, get the token<br>    if (method.meta?.isThirdPartyApi) {<br>      // Get token in an atomic way to prevent multiple processes from getting token simultaneously<br>      const accessTokenGetMethod = getAccessToken();<br>      let accessToken = await queryCache(accessTokenGetMethod);<br>      if (!accessToken) {<br>        // Will be cached after successful retrieval<br>        accessToken = await atomize(accessTokenGetMethod);<br>      }<br>      method.config.params.access_token = accessToken;<br>    }<br>  },<br>  l2Cache: redisAdapter,<br>});<br>const getAccessToken = () =&gt; thirdPartyAlova.Get(&#39;http://third-party.com/token&#39;, {<br>  params: {<br>    grant_type: &#39;client_credentials&#39;,<br>    client_id: process.env.THIRD_PARTY_CLIENT_ID,<br>    client_secret: process.env.THIRD_PARTY_CLIENT_SECRET<br>  },<br>  cacheFor: {<br>    mode: &#39;restore&#39;,<br>    expire: 1 * 3600 * 1000 // Two hours cache time<br>  }<br>});<br>const getThirdPartyUserInfo = userId =&gt; thirdPartyAlova.Get(&#39;http://third-party.com/user/info&#39;, {<br>  params: {<br>    userId<br>  },<br>  meta: {<br>    isThirdPartyApi: true<br>  }<br>});</pre><h3>Final Thoughts</h3><p>In addition to these, alova also provides distributed verification code sending and validation, request retry, and other server hooks. If you want to learn more, you can refer to <a href="https://alova.js.org/tutorial/server/strategy/">Server-Side Request Strategies</a>.</p><p>If you think alova is good, we sincerely hope you can <a href="https://alova.js.org/examples">try it out</a> and give us a free <a href="https://github.com/alovajs/alova">GitHub star</a>.</p><p>Visit the alovajs official website for more detailed information: <a href="https://alova.js.org/">alovajs Official Website</a>.</p><p>If you’re interested, you can join our community to get the latest updates first and communicate directly with the development team, sharing your ideas and suggestions.</p><ul><li><a href="https://alova.js.org/img/wechat_qrcode.jpg">Join WeChat group for discussions</a></li><li><a href="https://discord.gg/S47QGJgkVb">Join Discord community for discussions</a></li></ul><p>If you have any questions, you can join the above groups for consultation, or post in <a href="https://github.com/alovajs/alova/discussions">GitHub repository Discussions</a>. If you encounter problems, please submit them in <a href="https://github.com/alovajs/alova/issues">GitHub issues</a>, and we will resolve them as quickly as possible.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=808a53b652e7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hey there!]]></title>
            <link>https://medium.com/@huzhen555/hey-there-9f1015887b33?source=rss-9ff345d9fb22------2</link>
            <guid isPermaLink="false">https://medium.com/p/9f1015887b33</guid>
            <category><![CDATA[http-client]]></category>
            <category><![CDATA[axios]]></category>
            <category><![CDATA[fetch-api]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[alova]]></category>
            <dc:creator><![CDATA[Scott Hu]]></dc:creator>
            <pubDate>Sun, 03 Nov 2024 21:49:31 GMT</pubDate>
            <atom:updated>2024-11-03T21:49:31.610Z</atom:updated>
            <content:encoded><![CDATA[<p>Hey there! Today I want to share with you an incredibly useful feature — automatic data fetching. Have you ever encountered a situation where the user switches back to the app page, but the data is still in the old state? Or maybe you need to refresh the data periodically, but don’t want to do it manually? In these cases, the auto-fetch feature is a total lifesaver! It has really helped me a lot, making my app smarter and more fluid. Today, I’m going to show you how to implement this amazing feature using alovajs.</p><p>First, let me introduce you to alovajs. <strong>It’s a super powerful next-generation request tool</strong>. Not only does it provide a modern openapi generation solution, but it can also generate interface call code, TypeScript types, and interface documentation with just one click. Compared to libraries like react-query and swrjs, alovajs goes even further — it provides high-quality request strategies for various scenarios, allowing us to implement complex request logic with very little code.</p><p>I was truly amazed when I first started using alovajs. It can be a powerhouse on both the client-side and server-side (like Node.js, Deno, and Bun). It’s like alovajs has given my development work a pair of wings, making everything so much easier and more efficient.</p><p>Want to know more about alovajs? Head over to the official website at <a href="https://alova.js.org/">https://alova.js.org</a> and check it out! I’m sure you’ll be as captivated by its powerful features as I am.</p><h3>Automatic Data Fetching: Making Your App Smarter</h3><p>Now, let’s dive into how to implement automatic data fetching using alovajs. alovajs provides a super handy hook called useAutoRequest. <strong>It supports automatically fetching the latest data in scenarios like browser focus, tab switches, network reconnections, and polling.</strong></p><p>Let’s see how to use it:</p><pre>import { useAutoRequest } from &#39;alova/client&#39;;<br>const { loading, data, error } = useAutoRequest(() =&gt; method());</pre><p>It’s that simple! By default, it will automatically fetch data when the browser shows/hides, focuses, or reconnects to the network, and it will also automatically cancel the listener when the component is unmounted. How considerate!</p><h3>Customizable Configuration: Flexible for Various Scenarios</h3><p>But wait, there’s more! We can customize the configuration, like this:</p><pre>const { loading, data, error } = useAutoRequest(() =&gt; method(), {<br>  enableVisibility: true,  // Trigger on browser show/hide<br>  enableFocus: true,       // Trigger on browser focus<br>  enableNetwork: true,     // Trigger on network reconnection<br>  throttle: 1000,          // Throttle time to avoid frequent requests<br>  pollingTime: 2000        // Polling time, request every 2 seconds<br>});</pre><p>These configurations allow us to have fine-grained control over the auto-fetch behavior. It’s been a lifesaver for me! I once used this feature to solve a tricky real-time data update problem, and it significantly boosted my app’s performance.</p><h3>Pause Requests: Flexible Control</h3><p>Sometimes, we may need to pause the automatic requests, like when the user leaves the page but the component is not destroyed. Don’t worry, alovajs has considered this too:</p><pre>let pause = false;<br>useAutoRequest({<br>  // ...<br>  middleware(_, next) {<br>    if (!pause) {<br>      next();<br>    }<br>  }<br>});</pre><p>By controlling the pause variable, we can easily pause or resume the automatic requests. This feature was a huge help when I was developing an app that required frequent page switching - it ensured data timeliness while avoiding unnecessary requests.</p><h3>Cross-Platform Support: Automatic Requests Everywhere</h3><p>Finally, for non-browser environments, alovajs allows us to customize the listener functions. For example, in React Native, we can set up the network reconnection listener like this:</p><pre>import NetInfo from &#39;@react-native-community/netinfo&#39;;<br>useAutoRequest.onNetwork = (notify, config) =&gt; {<br>  const unsubscribe = NetInfo.addEventListener(({ isConnected }) =&gt; {<br>    isConnected &amp;&amp; notify();<br>  });<br>  return unsubscribe;<br>};</pre><p>This flexibility is amazing, allowing us to use the auto-fetch feature in any environment. I remember a time when I was developing a cross-platform app, and this feature saved me from writing a ton of repetitive code.</p><h3>Conclusion: alovajs Makes Development Easier</h3><p>In summary, alovajs’s automatic data fetching feature is incredibly useful! It not only makes our apps smarter, but also greatly reduces our workload. Say goodbye to the hassle of manually managing data refreshes, and let your app keep itself up-to-date.</p><p>Have you thought of using this feature to solve some of your previous tricky problems? Or do you have other use cases in mind? Feel free to share your ideas in the comments! And if you found this article helpful, don’t forget to give it a like. Let’s explore the endless possibilities of alovajs together!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9f1015887b33" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[react-query outdated? This new tool will double your efficiency, no cap]]></title>
            <link>https://medium.com/@huzhen555/react-query-outdated-this-new-tool-will-double-your-efficiency-no-cap-254e06b751b4?source=rss-9ff345d9fb22------2</link>
            <guid isPermaLink="false">https://medium.com/p/254e06b751b4</guid>
            <category><![CDATA[http-client]]></category>
            <category><![CDATA[alova]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[axios]]></category>
            <category><![CDATA[fetch-api]]></category>
            <dc:creator><![CDATA[Scott Hu]]></dc:creator>
            <pubDate>Sun, 03 Nov 2024 00:48:22 GMT</pubDate>
            <atom:updated>2024-11-03T00:48:22.644Z</atom:updated>
            <content:encoded><![CDATA[<p>Wow, my fellow front-end developer friends, I’ve recently discovered a super useful tool — the verification code request strategy! 🤩 This strategy has really been a lifesaver for me, especially in scenarios where I need to update data in real-time. It’s made my app so much smoother, and the user experience has skyrocketed as a result. I can’t wait to tell you all about this amazing thing!</p><p>🚀 alovajs: The Rising Star of Request Strategies</p><p>When it comes to the verification code request strategy, I have to mention the powerful tool called alovajs. alovajs is a next-generation request tool that not only simplifies the request process, but also provides a more modern openapi generation solution. <strong>Unlike libraries like react-query and swrjs, alovajs can generate interface call code, interface typescript type, and interface documentation with just one click.</strong> 🤯 This greatly shortens the collaboration distance between the front-end and back-end, making development much more efficient. To be honest, when I first started using it, I was completely blown away — I felt like my development efficiency went up by a whole level!</p><p>If you’re as interested in alovajs as I am, I strongly recommend you check out the official website: <a href="https://alova.js.org/">https://alova.js.org</a>. I’m sure you’ll be just as impressed by its powerful features as I am! 😎</p><p>🎯 Verification Code Request Strategy: Simple yet Powerful</p><p>Now, let’s take a look at how to use alovajs’s verification code request strategy. The usage method is so simple, it’ll surprise you! 🤩</p><p>First, we need to import useCaptcha from alovajs:</p><pre>import { useCaptcha } from &#39;alova/client&#39;;</pre><p>Then, we can use it like this:</p><pre>&lt;template&gt;<br>  &lt;input v-model=&quot;mobile&quot; /&gt;<br>  &lt;button<br>    @click=&quot;sendCaptcha&quot;<br>    :loading=&quot;sending&quot;<br>    :disabled=&quot;sending || countdown &gt; 0&quot;&gt;<br>    {{ loading ? &#39;发送中...&#39; : countdown &gt; 0 ? `${countdown}后可重发` : &#39;发送验证码&#39; }}<br>  &lt;/button&gt;<br>&lt;/template&gt;<br>&lt;script setup&gt;<br>  import { ref } from &#39;vue&#39;;<br>  import { apiSendCaptcha } from &#39;./api.js&#39;;<br>  import { useCaptcha } from &#39;alova/client&#39;;<br>  const mobile = ref(&#39;&#39;);<br>  const {<br>    // 发送状态<br>    loading: sending,<br>    // 调用sendCaptcha才会请求接口发送验证码<br>    send: sendCaptcha<br>  } = useCaptcha(() =&gt; apiSendCaptcha(mobile.value));<br>&lt;/script&gt;</pre><p>See? It’s that simple! 😲 useCaptcha handles all the complex connection management for us, so we can just focus on the business logic. You know, when I saw how easy it was to use this strategy, I felt like a total rockstar developer. I was able to handle real-time data updates with just a few lines of code! 🤩</p><p>And if you need to customize the countdown time, that’s easy too:</p><pre>useCaptcha(() =&gt; apiSendCaptcha(mobile.value), {<br>  // ...<br>  // highlight-start<br>  // Set the countdown to 20 seconds<br>  initialCountdown: 20<br>  // highlight-end<br>});</pre><p><strong>Using alovajs’s verification code request strategy makes real-time data updates so darn simple.</strong> 🔥 It not only provides a more concise and easy-to-use API, but also automatically manages the connections, greatly reducing our workload. I feel like this is a small revolution in front-end development! 🎉</p><p>🎉 Summary and Reflection</p><p>Let’s recap the key benefits of alovajs’s verification code request strategy:</p><ol><li><strong>Concise and easy-to-use API</strong>: It feels as natural as writing regular JavaScript code. 😎</li><li><strong>Automatic connection management</strong>: No more worrying about connection status handling. 🙌</li><li><strong>Flexible event binding</strong>: Easily handle various complex real-time data scenarios. 🤖</li></ol><p>These features allow us to focus more on the business logic, rather than getting bogged down in the implementation details. To be honest, after using alovajs, I feel like my development efficiency has increased by at least 30%! 🚀</p><p>However, I’ve also been thinking: Even though alovajs brings us so much convenience, should we also try to understand its underlying implementation principles? 🤔 After all, knowing the “why” behind the “what” can help us better troubleshoot and solve problems when they arise.</p><p>My fellow developer friends, what challenges have you encountered when dealing with real-time data updates? Has alovajs’s feature solved your pain points? Do you have similar thoughts? Feel free to share your ideas and experiences in the comments. Let’s discuss and progress together, and build even better user experiences! 💪</p><p>If you find this article helpful, don’t forget to give it a like. 👍 Your support is the driving force for me to continue sharing! I’ll see you next time, as we explore the wonderful world of front-end development! 🌟</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=254e06b751b4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Forget about axios, this new tool makes automatic data fetching a breeze!]]></title>
            <link>https://medium.com/@huzhen555/forget-about-axios-this-new-tool-makes-automatic-data-fetching-a-breeze-8bd83dbb1fa9?source=rss-9ff345d9fb22------2</link>
            <guid isPermaLink="false">https://medium.com/p/8bd83dbb1fa9</guid>
            <category><![CDATA[alova]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[http-client]]></category>
            <category><![CDATA[fetch-api]]></category>
            <category><![CDATA[axios]]></category>
            <dc:creator><![CDATA[Scott Hu]]></dc:creator>
            <pubDate>Fri, 01 Nov 2024 22:10:25 GMT</pubDate>
            <atom:updated>2024-11-01T22:10:25.109Z</atom:updated>
            <content:encoded><![CDATA[<p>Shocked? This form submission strategy is even stronger than react-query!</p><p>Hey, my fellow front-end developers! Today I’m going to share with you a super useful thing — the form submission strategy. To be honest, you guys must have had a headache with all the details of form submission, right? Don’t worry, I recently found a tool that really helped me a lot, and it makes form submission simple and efficient. Let me share this magical assistant with you today!</p><h3>alovajs: The Powerful Helper for Form Submission</h3><p>When it comes to form submission strategy, we can’t help but mention the awesome tool called alovajs. <strong>alovajs is a next-generation request tool that simplifies the request process</strong>. To be honest, it not only provides a more modern openapi generation solution, but also offers high-quality request strategies for various request scenarios. Compared to libraries like react-query and swrjs, alovajs is much smoother to use, allowing us to implement specific scenarios with very little code.</p><p>If you want to learn more about alovajs, you can check out the official website: <a href="https://alova.js.org/">https://alova.js.org</a>. Believe me, you’ll discover a whole new world of requests!</p><h3>alovajs’ Form Submission Strategy</h3><p>Now, let’s take a look at how alovajs’ form submission strategy is used. In my opinion, these features are really thoughtful!</p><h3>Basic Usage</h3><p>First, let’s look at the basic usage:</p><pre>const submitData = data =&gt; {<br>  return alovaInstance.Post(&#39;/api/submit&#39;, data);<br>};<br>const {<br>  loading: submiting,<br>  form,<br>  send: submit,<br>  onSuccess,<br>  onError,<br>  onComplete<br>} = useForm(<br>  formData =&gt; {<br>    return submitData(formData);<br>  },<br>  {<br>    initialForm: {<br>      name: &#39;&#39;,<br>      cls: &#39;1&#39;<br>    }<br>  }<br>);</pre><p>This code looks pretty simple, right? But it’s already handled a lot of details for us. When I first used it, I was really amazed by its conciseness!</p><h3>Automatic Form Reset</h3><p><strong>Automatic form reset after submission</strong>? No problem! Just set a parameter:</p><pre>useForm(submitData, {<br>  resetAfterSubmiting: true<br>});</pre><p>This feature really saved me a lot of trouble. No more manual form reset!</p><h3>Update Form Data</h3><p>Need to <strong>update form data</strong>? Also very simple:</p><pre>const { updateForm } = useForm(submitData, {<br>  initialForm: {<br>    name: &#39;&#39;,<br>    cls: &#39;1&#39;<br>  }<br>});<br>onSuccess(({ data }) =&gt; {<br>  updateForm({<br>    name: data.name,<br>    cls: data.cls<br>  });<br>});</pre><p>This feature is a lifesaver for editing forms!</p><h3>Form Draft Function</h3><p>alovajs also provides a <strong>form draft</strong> function, which can restore form data even after refreshing the page:</p><pre>useForm(submitData, {<br>  store: true<br>});</pre><p>To be honest, this feature has solved a lot of my troubles. No more worrying about losing data when accidentally refreshing the page!</p><h3>Multi-page/Multi-step Form</h3><p>The most surprising thing to me is its <strong>multi-page/multi-step form</strong> function. Just set an id, and you can share the same form data across different pages:</p><pre>// Component A<br>const returnStates = useForm(submitData, {<br>  initialForm: {<br>    step1Input: &#39;&#39;,<br>    step2Input: &#39;&#39;,<br>    step3Input: &#39;&#39;<br>  },<br>  id: &#39;testForm&#39;<br>});<br>// Component B, Component C<br>const returnStates = useForm(submitData, {<br>  id: &#39;testForm&#39;<br>});</pre><p>This way, we can easily handle complex multi-step forms. To be honest, this feature has saved me a lot of trouble!</p><h3>Conditional Filtering</h3><p>Finally, if you need to do conditional filtering, alovajs also provides a convenient way:</p><pre>const { send: searchData } = useForm(queryCity, {<br>  initialForm: {<br>    cityName: &#39;&#39;<br>  },<br>  immediate: true<br>});</pre><p>This feature is really handy for scenarios that require real-time searching!</p><h3>Summary</h3><p>After seeing all this, don’t you think alovajs’ form submission strategy is really powerful? <strong>It not only simplifies our code, but also helps us solve many common form problems</strong>. After using it, I feel my development efficiency has improved a lot, and the code has become much clearer and easier to understand.</p><p>So, how do you guys usually deal with form submission? Have you encountered any tricky problems? You might as well try alovajs, and it might bring you unexpected surprises. Welcome to share your thoughts and experiences in the comments, let’s progress together and build better front-end applications!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8bd83dbb1fa9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Axios is so last season, you gotta try this magical retry strategy]]></title>
            <link>https://medium.com/@huzhen555/axios-is-so-last-season-you-gotta-try-this-magical-retry-strategy-11dfebb17797?source=rss-9ff345d9fb22------2</link>
            <guid isPermaLink="false">https://medium.com/p/11dfebb17797</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[alova]]></category>
            <category><![CDATA[fetch-api]]></category>
            <category><![CDATA[http-client]]></category>
            <category><![CDATA[axios]]></category>
            <dc:creator><![CDATA[Scott Hu]]></dc:creator>
            <pubDate>Thu, 31 Oct 2024 22:19:36 GMT</pubDate>
            <atom:updated>2024-10-31T23:53:06.696Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello everyone! Recently, when I was developing a project, I found a super practical function — the automatic retry request strategy. You know, this little function really helped me a lot! Every time I handle a network request failure, I always have to write a lot of repetitive code, which is really annoying. But with this strategy, everything becomes so easy! Let me introduce it to you today.</p><h3>alovajs: More than just a regular request library</h3><p>When it comes to automatic retry request strategies, we have to mention the artifact alovajs. Alovajs is a brand new request tool, it is not just an ordinary request library. It provides a more modern openapi generation solution, which can generate interface call code, TypeScript types and interface documents with one click, eliminating the intermediate api document link, greatly shortening the distance of front-end and back-end collaboration. The best thing is that alovajs also provides high-quality request strategies for various request scenarios, including the automatic retry strategy we are going to talk about today. These strategies include stateful data, specific events and actions, and are smoother to use than react-query and swrjs. You only need a little code to implement requests in specific scenarios, which greatly improves development efficiency! Want to know more about alovajs? Go to the official website: <a href="https://alova.js.org/">https://alova.js.org</a>. I believe you will be amazed by its powerful functions!</p><h3>Automatic retry strategy</h3><p>Okay, let’s take a look at how powerful this automatic retry strategy is.</p><pre>import { useRetriableRequest } from &#39;alova/client&#39;;<br>const {<br>  loading,<br>  data,<br>  error,<br>  onError,<br>  onRetry,<br>  onFail,<br>  onSuccess,<br>  onComplete<br>} = useRetriableRequest(request);</pre><p>See, it’s that simple! Not only can you get the loading status, response data and error information of the request, but you can also bind various event callbacks. This is much more convenient than writing it ourselves, right?</p><h3>Customize the number of retries</h3><p>Sometimes we want the request to be automatically retried several times, which is also easy to achieve:</p><pre>const { send } = useRetriableRequest(request, {<br>  retry: 5<br>});</pre><p>Set the maximum number of retries to 5. It’s that simple. Of course, if you want to control the retry logic more flexibly, you can also pass in a function to dynamically determine it.</p><h3>Setting the retry delay</h3><p>Sometimes we want to have a certain delay between each retry, which is also easy to configure:</p><pre>useRetriableRequest(request, {<br>  backoff: {<br>    delay: 2000,<br>    multiplier: 2<br>  }<br>});</pre><p>With this setup, the first retry will be delayed by 2 seconds, the second by 4 seconds, the third by 8 seconds, etc. You can even add random jitter to make the retries more “random”.</p><h3>Manually stop retry</h3><p>If you need to manually stop retrying in some cases, it is also very simple:</p><pre>const { stop } = useRetriableRequest(request);<br>const handleStop = () =&gt; {<br>  stop();<br>};</pre><h3>End</h3><p>In general, the automatic retry strategy of alovajs is really a super practical function! It not only greatly simplifies the code of the retry logic, but also provides a variety of flexible configuration options to improve development efficiency. The most important thing is that it can help us solve many pain points in traditional request processing, such as retry count control, delay time setting, etc. These are very common requirements in daily development. With this strategy, we don’t have to implement them ourselves.<br>Have you encountered similar problems in development? Why not try the automatic retry strategy of alovajs, maybe it can help you. If you are already using it, welcome to share your experience in the comment area! Let’s discuss and make progress together!<br>Remember, technology is constantly improving, and we must keep up with the pace. Only by maintaining a passion for learning can we gain a foothold in this rapidly developing industry. Today’s sharing ends here, I hope it will be helpful to everyone. If you find it useful, don’t forget to like it! See you next time!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=11dfebb17797" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React-query is outdated? This new favorite makes cross-component requests simple in seconds!]]></title>
            <link>https://medium.com/@huzhen555/react-query%E5%B7%B2%E8%BF%87%E6%97%B6-%E8%BF%99%E4%B8%AA%E6%96%B0%E5%AE%A0%E8%AE%A9%E8%B7%A8%E7%BB%84%E4%BB%B6%E8%AF%B7%E6%B1%82%E7%A7%92%E5%8F%98%E7%AE%80%E5%8D%95-6dfc1f95c71b?source=rss-9ff345d9fb22------2</link>
            <guid isPermaLink="false">https://medium.com/p/6dfc1f95c71b</guid>
            <category><![CDATA[http-client]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[fetch-api]]></category>
            <category><![CDATA[axios]]></category>
            <category><![CDATA[alova]]></category>
            <dc:creator><![CDATA[Scott Hu]]></dc:creator>
            <pubDate>Wed, 30 Oct 2024 16:49:03 GMT</pubDate>
            <atom:updated>2024-10-31T23:55:42.621Z</atom:updated>
            <content:encoded><![CDATA[<p>Wow, my front-end friends, I recently discovered a super cool new technology! Do you know that this thing can easily handle cross-component requests, it is simply a savior of front-end development!</p><h3>alovajs: the next generation request tool</h3><p>Compared to the familiar react-query and swrjs, alovajs can be said to be the next generation of request tools. It not only simplifies the request process, but also provides a modern openapi generation solution. Imagine that you only need one click to generate interface call code, TypeScript type and interface documentation.</p><p>Isn’t it super convenient?<br>To learn more about the power of alovajs, go to its official website <a href="https://alova.js.org/">https://alova.js.org</a>!</p><h3>Cross-component triggering requests: the killer feature of alovajs</h3><p>But today I want to share with you a great feature of alovajs — — triggering requests across components. You must have had a headache dealing with this kind of requirement before, right? For example, you updated the menu data in one component, and then want to re-pull the latest data in another component. It’s really too troublesome to use state management tools such as Vuex and Redux to handle this!</p><p>But with Alovajs, everything becomes so easy. We only need to use actionDelegationMiddleware in component A to delegate the operation function of useRequest, and then in any other component (such as component B), we can easily trigger the request of component A through accessAction.</p><pre>// Component A<br>import { actionDelegationMiddleware } from &#39;alova/client&#39;;<br>useRequest(queryTodo, {<br>  middleware: actionDelegationMiddleware(&#39;updateTodo&#39;)<br>});</pre><pre>// Component B <br>import { accessAction } from &#39;alova/client&#39;;<br>accessAction(&#39;updateTodo&#39;, delegatedActions =&gt; {<br>  delegatedActions.send(); // trigger the request in component A<br>});</pre><p>Cool, right? Now we can update data from anywhere without worrying about component hierarchy limitations.</p><p>Alovajs also supports batch triggering of action functions. You can use the same delegate name in multiple components, and then trigger them all at once in another component. You can also use regular expressions to batch trigger requests that meet the conditions. This flexibility is really great, making our code structure clearer and the logic more centralized!</p><h3>End</h3><p>In short, through the cross-component trigger request function of alovajs, we can greatly improve development efficiency and make the code easier to maintain. To be honest, since I used alovajs, I feel that my code level has improved a lot!<br>Dear friends, how do you usually deal with this kind of demand? Have you encountered any tricky problems? Why not try alovajs, maybe it can bring you unexpected surprises! Finally, I would like to ask everyone to think about it: In your project, are there any places that can be optimized by triggering requests across components? What changes will using alovajs bring to your development process? Welcome to share your ideas and experiences in the comment area, let us make progress together!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6dfc1f95c71b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hey there!]]></title>
            <link>https://medium.com/@huzhen555/hey-there-d40cd93d2e1a?source=rss-9ff345d9fb22------2</link>
            <guid isPermaLink="false">https://medium.com/p/d40cd93d2e1a</guid>
            <category><![CDATA[alova]]></category>
            <category><![CDATA[fetch-api]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[http-client]]></category>
            <category><![CDATA[axios]]></category>
            <dc:creator><![CDATA[Scott Hu]]></dc:creator>
            <pubDate>Tue, 29 Oct 2024 22:48:51 GMT</pubDate>
            <atom:updated>2024-10-29T22:48:51.971Z</atom:updated>
            <content:encoded><![CDATA[<p>Hey there! Today I want to share with you a topic that has really struck a chord with me — the <strong>automatic retry request strategy</strong>. This feature has been an absolute lifesaver for me! When dealing with network requests, especially in unstable network environments, the auto-retry strategy has become my trusted companion. It’s made my app much more robust and significantly improved the user experience. Today, I’d love to tell you all about the auto-retry request strategy in alovajs — I’m sure you’ll be just as excited about it as I am! <strong>What is alovajs?</strong></p><p>First, let me introduce you to alovajs. alovajs is a next-generation request tool, and it’s much more than just a simple HTTP client. Unlike libraries like react-query and swrjs, alovajs provides a more modern OpenAPI generation solution. It can generate the interface call code, TypeScript types, and API documentation all with a single click, greatly simplifying the front-end and back-end collaboration process. Even better, alovajs also offers a variety of high-quality request strategies that can meet almost all specific request scenario needs. Using alovajs, you only need a little bit of code to implement complex request logic — it’s been a real game-changer for me.</p><p>If you want to learn more about alovajs, I strongly recommend you check out the official website: <a href="https://alova.js.org/">https://alova.js.org</a>. There, you’ll find more detailed documentation and examples, and I’m sure you’ll discover even more interesting features. <strong>Using the Auto-Retry Request Strategy</strong></p><p>Now, let’s dive into how to use the auto-retry request strategy in alovajs. This feature is truly a lifesaver, especially for important requests. <strong>Basic Usage</strong></p><pre>import { useRetriableRequest } from &#39;alova/client&#39;;<br>const {<br>  loading,<br>  data,<br>  error,<br>  onError,<br>  onRetry,<br>  onFail,<br>  onSuccess,<br>  onComplete<br>} = useRetriableRequest(request);</pre><p>This code looks pretty simple, right? But it can handle a lot of complex situations. By default, it will retry up to 3 times, with a 1-second delay between each retry. This already covers most needs. <strong>Customizing Retry Count</strong></p><p>If you need more control, alovajs provides plenty of options. For example, you can customize the maximum number of retries:</p><pre>const { send } = useRetriableRequest(request, {<br>  retry: 5<br>});</pre><p>This will allow it to retry up to 5 times. <strong>Dynamic Retry Conditions</strong></p><p>Sometimes, you may want to decide whether to continue retrying based on the specific error. alovajs has considered this as well:</p><pre>useRetriableRequest(request, {<br>  retry(error, ...args) {<br>    return /network timeout/i.test(error.message);<br>  }<br>});</pre><p>This code will continue retrying if it encounters a network timeout error. <strong>Customizing Retry Delay</strong></p><p>alovajs also allows you to customize the retry delay:</p><pre>useRetriableRequest(request, {<br>  backoff: {<br>    delay: 2000,<br>    multiplier: 2<br>  }<br>});</pre><p>With this configuration, the first retry will wait 2 seconds, the second 4 seconds, the third 8 seconds, and so on. This exponential backoff strategy is very useful in many scenarios. <strong>Manually Stopping Retries</strong></p><p>Finally, if you need to manually stop the retries, alovajs provides this functionality too:</p><pre>const { stop } = useRetriableRequest(request, {<br>  // ...<br>});<br>const handleStop = () =&gt; {<br>  stop();<br>};</pre><p>This can be handy in certain special cases, like when the user actively cancels an operation.</p><p><strong>Conclusion</strong></p><p>The auto-retry request strategy in alovajs has really impressed me. It’s not only powerful, but also extremely flexible to use. With this feature, we can effectively handle various network exceptions and improve the reliability of our applications.</p><p>In my projects, using this feature has significantly reduced user-reported network issues. It’s truly enhanced the user experience.</p><p>What do you think about this feature? Are you interested in trying it out in your own projects? Feel free to share your thoughts in the comments. If you found this article helpful, don’t forget to give it a like! Let’s explore together how we can make our applications more stable and reliable.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d40cd93d2e1a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Shocking! This cross-component trick will make react-query users sweat]]></title>
            <link>https://medium.com/@huzhen555/shocking-this-cross-component-trick-will-make-react-query-users-sweat-76d9774e92e7?source=rss-9ff345d9fb22------2</link>
            <guid isPermaLink="false">https://medium.com/p/76d9774e92e7</guid>
            <category><![CDATA[alova]]></category>
            <category><![CDATA[fetch-api]]></category>
            <category><![CDATA[http-client]]></category>
            <category><![CDATA[axios]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Scott Hu]]></dc:creator>
            <pubDate>Mon, 28 Oct 2024 15:30:15 GMT</pubDate>
            <atom:updated>2024-10-28T15:30:15.320Z</atom:updated>
            <content:encoded><![CDATA[<p>Wow, my fellow front-end developers! Today, I want to share with you an incredibly useful feature — <strong>跨组件触发请求</strong>. Are you often racking your brain trying to implement a smooth pagination list? Don’t worry, I’ve discovered a super handy tool that has really helped me a lot! I’m so excited I could jump for joy! <strong>alovajs</strong> — have you heard of it? It’s a next-generation request tool, not just a simple HTTP client. Unlike react-query and swrjs, alovajs provides a complete solution for requests. It can not only handle basic API calls, but also optimize complex data interaction scenarios, such as the pagination list we’re going to discuss today.</p><p>If you want to dive deeper into alovajs’ powerful features, be sure to check out the official website <a href="https://alova.js.org/">https://alova.js.org</a>. I’m sure you’ll discover a whole new world of efficient data requests!</p><p>Now, let’s see how alovajs makes cross-component request triggering a breeze.</p><p>In the past, if you wanted to trigger a request in one component from another component, you had to save the data to the Store and complete it by dispatching an Action. Now, you can use this middleware to <strong>eliminate the component hierarchy restriction</strong> and quickly trigger the operation functions of any request in any component.</p><p>For example, you can re-trigger the request for the sidebar menu after updating the menu data in a certain component, thereby refreshing the data. After operating on the list data, you can trigger the list update.</p><h3>Features</h3><ul><li>Delegate the operation functions of any alova use hook;</li><li>Trigger the delegated operation functions from any position;</li></ul><h3>Usage</h3><h3>Basic usage</h3><blockquote><em>Taking vue3 as an example, the usage is the same in react and svelte.</em></blockquote><p>Use actionDelegationMiddleware to delegate the operation functions of useRequest in component A.</p><pre>import { actionDelegationMiddleware } from &#39;alova/client&#39;;</pre><pre>useRequest(queryTodo, {<br>  // ...<br>  middleware: actionDelegationMiddleware(&#39;actionName&#39;)<br>});</pre><p>In any component (e.g. component B), use accessAction to pass in the specified delegation name to trigger the operation functions of useRequest in component A.</p><pre>import { accessAction } from &#39;alova/client&#39;;</pre><pre>accessAction(&#39;actionName&#39;, delegatedActions =&gt; {<br>  // Call the send function in component A<br>  delegatedActions.send();</pre><pre>  // Call the abort function in component A<br>  delegatedActions.abort();<br>});</pre><h3>Batch trigger operation functions</h3><p>In the above example, we used accessAction to trigger the operation function of a use hook, but in fact, the same delegation name will not overwrite each other, but will be saved in a set, and we can use this name to trigger their delegated functions at the same time.</p><pre>import { actionDelegationMiddleware } from &#39;alova/client&#39;;</pre><pre>useRequest(queryTodo, {<br>  // ...<br>  middleware: actionDelegationMiddleware(&#39;actionName1&#39;)<br>});</pre><pre>import { actionDelegationMiddleware } from &#39;alova/client&#39;;</pre><pre>useRequest(queryTodo, {<br>  // ...<br>  middleware: actionDelegationMiddleware(&#39;actionName1&#39;)<br>});</pre><pre>import { accessAction } from &#39;alova/client&#39;;</pre><pre>// Since it will match the delegated hooks of component C and component D, the callback function will be executed twice<br>accessAction(&#39;actionName1&#39;, delegatedActions =&gt; {<br>  // Call the send function in component C and component D<br>  delegatedActions.send();</pre><pre>  // Call the abort function in component C and component D<br>  delegatedActions.abort();<br>});</pre><p>Additionally, you can use regular expressions in accessAction to batch trigger the operation functions that meet the delegation name conditions.</p><pre>import { actionDelegationMiddleware } from &#39;alova/client&#39;;</pre><pre>useRequest(queryTodo, {<br>  // ...<br>  middleware: actionDelegationMiddleware(&#39;prefix_name1&#39;)<br>});</pre><pre>import { actionDelegationMiddleware } from &#39;alova/client&#39;;</pre><pre>useRequest(queryTodo, {<br>  // ...<br>  middleware: actionDelegationMiddleware(&#39;prefix_name2&#39;)<br>});</pre><pre>import { accessAction } from &#39;alova/client&#39;;</pre><pre>// Since it will match the delegated hooks of component F and component G, the callback function will be executed twice<br>accessAction(/^prefix_/, delegatedActions =&gt; {<br>  // Call the send function in component F and component G<br>  delegatedActions.send();</pre><pre>  // Call the abort function in component F and component G<br>  delegatedActions.abort();<br>});</pre><p>This feature really makes my life easier when dealing with cross-component data synchronization. No more headaches about data consistency! And the best part is, it’s so easy to use. I’m surprised react-query and axios haven’t come up with something like this yet.</p><p>If you’re dealing with complex component interactions in your daily development, I highly recommend giving alovajs a try. This powerful tool can significantly improve your development efficiency and user experience.</p><p>What do you usually do to handle cross-component requests? Have you encountered any interesting problems or solutions? Feel free to share your experiences in the comments! Let’s discuss and learn from each other. I can’t wait to hear your thoughts!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=76d9774e92e7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Query Outdated? The New Generation of Request Tool is Here]]></title>
            <link>https://medium.com/@huzhen555/react-query-outdated-the-new-generation-of-request-tool-is-here-d57ee5572b58?source=rss-9ff345d9fb22------2</link>
            <guid isPermaLink="false">https://medium.com/p/d57ee5572b58</guid>
            <category><![CDATA[fetch-api]]></category>
            <category><![CDATA[alova]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[axios]]></category>
            <category><![CDATA[http-client]]></category>
            <dc:creator><![CDATA[Scott Hu]]></dc:creator>
            <pubDate>Sun, 27 Oct 2024 20:39:53 GMT</pubDate>
            <atom:updated>2024-10-27T20:39:53.246Z</atom:updated>
            <content:encoded><![CDATA[<p>Attention-grabbing title: <strong>React Query Outdated? The New Generation of Request Tool is Here</strong></p><p>Hey, everyone! Today, I want to share with you a topic that has got me really excited — the data fetching and preloading strategy of alovajs. You know what? This strategy has been a real lifesaver for me! It not only made my code more concise, but also greatly improved the user experience. To be honest, I can’t help but sigh with admiration every time I use this feature. Today, I’ll introduce you to the amazing tool alovajs and how it makes pagination list requests so simple.</p><h3>What is alovajs?</h3><p>alovajs is a next-generation request tool. Unlike libraries like react-query and swrjs, <strong>alovajs provides a complete request solution.</strong> It can not only generate interface call code, TypeScript types, and interface documentation, but also offers high-quality request strategies for various scenarios. These strategies include stateful data, specific events, and actions, making it smoother to use than other libraries.</p><p>Intrigued to learn more about alovajs? You can visit their official website: <a href="https://alova.js.org/">https://alova.js.org</a>. I’m sure you’ll be as impressed by its powerful features as I am.</p><h3>Data Fetching and Preloading: Effortless and Efficient</h3><p>Now, let’s dive into how alovajs’ data fetching and preloading strategy works. <strong>This feature has really made my development experience a joy!</strong></p><h3>Basic Setup</h3><p>First, we need to define a query function:</p><pre>const queryStudents = (page, pageSize) =&gt;<br>  alovaInstance.Get(&#39;/students&#39;, {<br>    params: {<br>      page,<br>      pageSize<br>    }<br>  });</pre><p>Then, we can use the useFetcher hook in our component:</p><pre>&lt;template&gt;<br>  &lt;div v-if=&quot;loading&quot;&gt;Fetching...&lt;/div&gt;<br>  &lt;!-- List view --&gt;<br>&lt;/template&gt;<br>&lt;script setup&gt;<br>  import { useFetcher } from &#39;alova/client&#39;;<br>  const getTodoList = currentPage =&gt; {<br>    return alovaInstance.Get(&#39;/todo/list&#39;, {<br>      cacheFor: 60000,<br>      params: {<br>        currentPage,<br>        pageSize: 10<br>      }<br>    });<br>  };<br>  const {<br>    loading,<br>    error,<br>    onSuccess,<br>    onError,<br>    onComplete,<br>    fetch<br>  } = useFetcher({<br>    updateState: false<br>  });<br>  const currentPage = ref(1);<br>  const { data } = useWatcher(() =&gt; getTodoList(currentPage.value), [currentPage], {<br>    immediate: true<br>  }).onSuccess(() =&gt; {<br>    // After the current page is successfully loaded, pass in the method instance of the next page to preload the data of the next page<br>    fetch(getTodoList(currentPage.value + 1));<br>  });<br>&lt;/script&gt;</pre><p><strong>This hook is so powerful!</strong> It not only provides basic features like loading status, list data, and page information, but also supports automatic management of pagination data and preloading. I feel my development efficiency has improved a lot with this tool.</p><h3>Append Mode: Easy Infinite Scrolling</h3><p>If you want to implement an infinite scrolling effect, you just need to enable the append mode:</p><pre>useFetcher((page, pageSize) =&gt; queryStudents(page, pageSize), {<br>  append: true<br>});</pre><p>It’s that simple! I still remember how tedious it was to implement this feature in the past. Now, it’s a breeze.</p><h3>Preloading: Smooth User Experience</h3><p>alovajs also provides a preloading feature to enhance the user experience. <strong>This feature is so thoughtful!</strong> If you don’t need this feature, you can disable it like this:</p><pre>useFetcher((page, pageSize) =&gt; queryStudents(page, pageSize), {<br>  preloadPreviousPage: false,<br>  preloadNextPage: false<br>});</pre><h3>Filtering: Smart and Efficient</h3><p>For lists with filtering conditions, alovajs also provides a simple solution:</p><pre>const studentName = ref(&#39;&#39;);<br>const clsName = ref(&#39;&#39;);<br>useFetcher((page, pageSize) =&gt; queryStudents(page, pageSize, studentName.value, clsName.value), {<br>  watchingStates: [studentName, clsName],<br>  debounce: 300<br>});</pre><p><strong>This feature is so thoughtful!</strong> It automatically listens to changes in the filtering conditions and supports debouncing, making our code more concise and efficient. Every time I use this feature, I can’t help but exclaim: “This is the development experience I’ve been dreaming of!”</p><h3>Conclusion</h3><p>In summary, alovajs’ data fetching and preloading strategy has really impressed me. It not only simplifies our code, but also provides many thoughtful features, such as automatic management of pagination data, preloading, and filtering condition monitoring. This allows us to focus more on the business logic, rather than being bogged down by tedious data processing. <strong>Using alovajs, I feel my development efficiency has improved a lot, and the code quality has also gotten better.</strong></p><p>Fellow developers, how do you usually handle pagination list requests? Have you encountered any tricky problems? Feel free to share your experiences and thoughts in the comments. If you find this article helpful, don’t forget to give it a like! Let’s explore and progress together!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d57ee5572b58" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>