From 9180a1e565eab7fed402febb8bc7decbf5121098 Mon Sep 17 00:00:00 2001 From: Arda Erzin Date: Mon, 9 Dec 2024 13:33:19 +0100 Subject: [PATCH] enhance(frontend): approach to use mutations with swr --- agenta-web/README.md | 41 ++++++++++++++++++++++++++++++++++++++++- 1 file changed, 40 insertions(+), 1 deletion(-) diff --git a/agenta-web/README.md b/agenta-web/README.md index 56a3ab457e..7d10199c6a 100644 --- a/agenta-web/README.md +++ b/agenta-web/README.md @@ -179,7 +179,12 @@ This structure supports: ### Data Fetching Best Practices -We recommend using SWR with Axios for data fetching instead of useEffect patterns. This helps achieve cleaner code while simplifying management of fetch states. +We recommend using SWR with Axios for data fetching instead of useEffect patterns. This helps achieve cleaner code while, + +- simplifying management of fetch states. +- handling cache better +- having a more interactive UI by revalidating in background +- utilizing optimistic mutations. #### Example: Converting useEffect Data Fetching to SWR with Axios @@ -235,6 +240,8 @@ function MyApp({ Component, pageProps }) { export default MyApp; ``` +and data can be then be fetched in a way that fits react mental model inside the component: + ```javascript import useSWR from 'swr'; @@ -253,3 +260,35 @@ function Component() { ); } ``` + +Mutations can be triggered via Swr in the following way + +```javascript +import useSWRMutation from 'swr/mutation' + +async function sendRequest(url, { arg }: { arg: { username: string }}) { + return fetch(url, { + method: 'POST', + body: JSON.stringify(arg) + }).then(res => res.json()) +} + +function App() { + const { trigger, isMutating } = useSWRMutation('/api/user', sendRequest, /* options */) + + return ( + + ) +} +```