diff --git a/documentation/blog/2023-01-03-use-swr.md b/documentation/blog/2024-07-19-use-swr.md
similarity index 72%
rename from documentation/blog/2023-01-03-use-swr.md
rename to documentation/blog/2024-07-19-use-swr.md
index 5062ff92f80f..f31f6a176ed5 100644
--- a/documentation/blog/2023-01-03-use-swr.md
+++ b/documentation/blog/2024-07-19-use-swr.md
@@ -4,10 +4,12 @@ description: Introduction to SWR and useSwr for Client-Side Data Fetching
slug: data-fetching-next-js-useswr
authors: michael
tags: [nextjs]
-image: https://refine.ams3.cdn.digitaloceanspaces.com/blog/2023-01-03-use-swr/social.png
+image: https://refine.ams3.cdn.digitaloceanspaces.com/blog/2023-01-03-use-swr/social-2.png
hide_table_of_contents: false
---
+**This article was last updated on July 19, 2024, to add sections for Error Handling, Mutations and Caching Strategies with SWR.**
+
## Introduction
Data is unquestionably an important component of any modern web application today. And, as the web evolves and innovates, new methods of interacting with this data must emerge in order to provide users with a better experience when interacting with our applications.
@@ -18,18 +20,6 @@ SWR is one of the most powerful client-side data fetching libraries for frontend
Whether you are new to React.js or an experienced developer looking to optimize your data fetching strategy, SWR is a powerful tool worth considering! Now, let's get started!
-Steps we'll cover:
-
-- [What is SWR and useSWR?](#what-is-swr-and-useswr)
-- [Setting up an Example App With SWR](#setting-up-an-example-app-with-swr)
-- [Additional Features of SWR](#additional-features-of-swr)
-
-## Prerequisites
-
-To follow along well with this tutorial, it's essential that you have basic knowledge of JavaScript and React. SWR is a library for use with React and its frameworks, so it's required that you're familiar with the basics of both of these technologies.
-
-In addition, make sure you have [Node](https://nodejs.org/) installed on your computer before continuing.
-
## What is SWR and `useSWR`?
SWR is an acronym for stale-while-revalidate. It's a lightweight React.js library with hooks for data fetching on the client-side. SWR is bootstrapped with various hooks that are used for various performance improvement techniques such as data caching, re-validation, pagination, and many others.
@@ -480,12 +470,126 @@ export default function App() {
}
```
-
-
+## Mutations with SWR
+
+I wanted to share some details about handling mutations with SWR to help us efficiently manage data updates in our React applications. Here are some practical tips and examples:
+
+SWR provides an excellent way to mutate data, which means updating or changing the cached data. This is useful for operations like creating, updating, or deleting records. Using the `mutate` function, we can optimistically update the UI and revalidate the data in the background.
+
+Here’s a simple example of how to use `mutate` with SWR:
+
+```javascript
+import useSWR, { mutate } from "swr";
+
+const fetcher = (url) => fetch(url).then((res) => res.json());
+
+const MyComponent = () => {
+ const { data, error } = useSWR("/api/data", fetcher);
+
+ const handleUpdate = async () => {
+ // Optimistically update the data
+ mutate("/api/data", newData, false);
+
+ // Send the update request to the server
+ await fetch("/api/data", {
+ method: "POST",
+ body: JSON.stringify(newData),
+ });
+
+ // Revalidate the data
+ mutate("/api/data");
+ };
+
+ if (error) return
Failed to load data. Please try again later.
;
+ if (!data) return
Loading...
;
+
+ return (
+
+ {data.map((item) => (
+
{item.name}
+ ))}
+
+
+ );
+};
+
+export default MyComponent;
+```
+
+In this example, we optimistically update the cached data before sending the update request to the server. After the server request completes, we revalidate the data to ensure it is up-to-date.
+
+### Handling Mutations
+
+**Optimistic UI Updates**: SWR allows you to update the UI optimistically, which means reflecting the changes immediately without waiting for the server response. This provides a better user experience.
+
+```javascript
+mutate("/api/data", newData, false); // Optimistically update data
+```
+
+**Revalidation**: After performing the mutation, you should revalidate the data to ensure consistency.
+
+```javascript
+mutate("/api/data"); // Revalidate data
+```
+
+**Error Handling**: Handle errors gracefully to ensure the UI doesn’t break when there are issues with the mutation.
+
+```javascript
+const handleUpdate = async () => {
+ try {
+ mutate("/api/data", newData, false);
+ await fetch("/api/data", {
+ method: "POST",
+ body: JSON.stringify(newData),
+ });
+ mutate("/api/data");
+ } catch (error) {
+ console.error("Failed to update data:", error);
+ }
+};
+```
+
+## Error Handling with SWR
+
+I wanted to share some insights on handling errors gracefully when using SWR for data fetching in our React projects. Here are some strategies and examples that might help:
+
+When using the `useSWR` hook, handling errors is straightforward. The hook returns an `error` object that we can use to display error messages or fallback content to the user.
+
+Here's a simple example:
+
+```javascript
+import useSWR from "swr";
+
+const fetcher = (url) => fetch(url).then((res) => res.json());
+
+const MyComponent = () => {
+ const { data, error } = useSWR("/api/data", fetcher);
+
+ if (error) return
Failed to load data. Please try again later.
;
+ if (!data) return
Loading...
;
+
+ return (
+
+ {/* Render your data here */}
+ {data.map((item) => (
+
{item.name}
+ ))}
+
+ );
+};
+
+export default MyComponent;
+```
+
+In this example, the component first checks if there's an error. If an error is detected, it displays a friendly error message. If there's no error but the data is still being fetched, it shows a loading indicator. Once the data is successfully fetched, it renders the data.
+
+### Tips for Handling Errors
+
+**Show User-Friendly Messages**: Always provide a clear and concise error message that guides the user on what went wrong and possible actions they can take.
+**Use a Fallback UI**: In case of errors, provide a fallback UI so that the application doesn't break. This can be a simple message or a more sophisticated error boundary.
+**Log Errors for Debugging**: Use logging tools to capture errors for debugging purposes. This helps in understanding and fixing issues faster.
+
+Implementing these strategies can make our applications more robust and improve the user experience.
### SWRDevTools
@@ -516,6 +620,75 @@ You can read more about using TypeScript with SWR [here](https://swr.vercel.app/
This section only touched on a few of SWR's many capabilities, so your first encounter with it will not be overwhelming. You can however, check the [documentation](https://swr.vercel.app/docs/getting-started) for other features that might interest you.
+## Caching Strategies with SWR
+
+I wanted to share some insights on caching strategies with SWR to improve the performance and user experience of our React applications. Here are some practical tips and examples that might help:
+
+SWR automatically caches data to optimize performance and reduce the number of network requests. However, there are several ways to customize caching to suit specific needs.
+
+Here's an example of basic caching with SWR:
+
+```javascript
+import useSWR from "swr";
+
+const fetcher = (url) => fetch(url).then((res) => res.json());
+
+const MyComponent = () => {
+ const { data, error } = useSWR("/api/data", fetcher);
+
+ if (error) return
Failed to load data. Please try again later.
;
+ if (!data) return
Loading...
;
+
+ return (
+
+ {data.map((item) => (
+
{item.name}
+ ))}
+
+ );
+};
+
+export default MyComponent;
+```
+
+In this example, SWR automatically caches the data fetched from the API.
+
+### Custom Caching Strategies
+
+**Cache Time Control**: You can set a specific cache time for your data. This is useful if the data doesn't change frequently.
+
+```javascript
+const { data, error } = useSWR("/api/data", fetcher, {
+ refreshInterval: 60000,
+}); // Refresh every 60 seconds
+```
+
+**Revalidation**: SWR can revalidate the cache when the user focuses on the window or when network status changes. This ensures users always see the most up-to-date data.
+
+```javascript
+const { data, error } = useSWR("/api/data", fetcher, {
+ revalidateOnFocus: true,
+ revalidateOnReconnect: true,
+});
+```
+
+**Manual Cache Management**: Sometimes, you may want to manually manage the cache, especially when dealing with real-time data updates or invalidations.
+
+```javascript
+import useSWR, { mutate } from "swr";
+
+// Manually mutate the cache
+mutate("/api/data", newData, false); // Update the cache without revalidation
+```
+
+### Tips for Effective Caching
+
+**Set Reasonable Cache Intervals**: Depending on how frequently your data changes, set appropriate cache refresh intervals.
+**Use Conditional Fetching**: Fetch data conditionally based on certain criteria to avoid unnecessary requests.
+**Combine with Other State Management Libraries**: SWR can be combined with other state management libraries like Redux or Zustand for more complex scenarios.
+
+By implementing these caching strategies, we can ensure our applications are more efficient and provide a smoother experience for users.
+
## Conclusion
In this article, we learned about the basics of SWR, its importance in developing modern web applications, and how you can get started with it. We also created an example application in React and explored some capabilities of SWR to see its use cases and benefits over other conventional client-side data fetching methods.