Skip to content

Commit

Permalink
enhance(frontend): approach to use mutations with swr
Browse files Browse the repository at this point in the history
  • Loading branch information
ardaerzin committed Dec 9, 2024
1 parent 311a82f commit 9180a1e
Showing 1 changed file with 40 additions and 1 deletion.
41 changes: 40 additions & 1 deletion agenta-web/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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';

Expand All @@ -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 (
<button
disabled={isMutating}
onClick={async () => {
try {
const result = await trigger({ username: 'johndoe' }, /* options */)
} catch (e) {
// error handling
}
}}
>
Create User
</button>
)
}
```

0 comments on commit 9180a1e

Please sign in to comment.