Fixing the SWR Cache Key Issue with Axios in React and Next.js

preview_player
Показать описание
---

Visit these links for original content and any more details, such as alternate solutions, latest updates/developments on topic, comments, revision history etc. For example, the original title of the Question was: SWR seems to cache two different requests under same cache key. How do I fix this?

If anything seems off to you, please feel free to write me at vlogize [AT] gmail [DOT] com.
---

Understanding the Problem

Using SWR, you can fetch data in an efficient way, but when two different requests (like an OPTIONS and a GET request) share the same URL, they will be cached under the same key by default. This results in receiving unexpected data whenever you try to fetch data for a different request type.

Here’s an example from the code:

[[See Video to Reveal this Text or Code Snippet]]

Both are fetching from the same endpoint, leading to confusion over which type of data is being retrieved when they are executed.

Solution: Create Unique Cache Keys

To resolve this caching issue, you need to use unique cache keys for each request type. Here are two clearly defined ways to accomplish this:

1. Using an Object as a Cache Key

You can create a composite key using both the URL and the request method. Here’s how you can adjust your useSWR hook:

[[See Video to Reveal this Text or Code Snippet]]

Adjusting the Fetcher Function

You will also need to modify your fetcher function to accommodate the object format:

[[See Video to Reveal this Text or Code Snippet]]

2. Using an Array as a Cache Key

Alternatively, you can use an array as your cache key, although this approach can be less clear:

[[See Video to Reveal this Text or Code Snippet]]

Example Implementation

This is how you would integrate these solutions into your component code:

[[See Video to Reveal this Text or Code Snippet]]

With these adjustments, SWR will handle each type of request distinctly, using unique keys for caching, and alleviate the issues of data collisions.

Conclusion

Now, you can confidently use SWR and Axios without the fear of cached requests interfering with each other. Happy coding!
Рекомендации по теме
welcome to shbcf.ru