Replies: 5 comments 1 reply
-
First, SWR is not intended to do POST requests, only GET requests, this is because SWR will trigger the request multiple times and that will cause unexpected behaviors if you do POST/PUT/PATCH/DELETE requests. Ignoring that, I would do: function fetcher(url, username, password) {
return fetch(url, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ username, password }),
}).then(res => res.json());
}
export function useUser(username, password) {
const { data, mutate, error } = useSWR(
["/login", username, password],
fetcher,
);
const loading = !data && !error;
const loggedOut = error && error.status === 403;
console.log("swr data", data);
console.log("swr error", error);
return {
loading,
loggedOut,
user: data,
mutate,
};
}
const { user } = useUser("my-username", "my-strong-password"); Something like that, but remember, you should not use SWR to POST, in your case, this will cause the user to log-in multiple times. |
Beta Was this translation helpful? Give feedback.
-
Thank you. How would you normally do authentication with swr? any module i should look into? |
Beta Was this translation helpful? Give feedback.
-
What I usually do is to use a cookie to store the user token, this cookie will be sent automatically by the browser with every request to the API. And to authenticate, I send the credentials in a POST inside an even handler and once I get the token in the response I store it in a cookie. I also usually have a useCurrentUser hook which requests an endpoint of the API to get the current user, the endpoint give me the user data based on the cookie. |
Beta Was this translation helpful? Give feedback.
-
Alright cool! Is there any full example? |
Beta Was this translation helpful? Give feedback.
-
The example in the website https://swr.vercel.app/examples/auth |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
I fail to understand how i would pass username and password to the useUser function.
useUser.js
The "Authentication example" has this as login function
Which i find very diffuse. Is my method of logging in weird? Am i allowed to think that the example is not complete / thorough enough?
I know i "could" pass username and password with useSWR(['/login', username, password'], fetcher). But that doesn't really help. Since i'm importing the useUser function from index.js.
Should i pass username and password through this?
It just doesnt feel right since im not seeing that anywhere in the tutorials. I'm pretty lost, please help
Beta Was this translation helpful? Give feedback.
All reactions