I’m doing rescript yet again, but in a slightly bigger project. This time, I’m starting with auth because… yes?
But I’m kinda lost on implementation details. How should I do something that is very mutable (and non-functional programming) + How can I integrate that with react (that part I know, but with js, not rescript).
I tried contexts with the following code, but I remembered that it should be immutable in rescript, so I don’t know how that would be possible.
type t =
| Guest
| Authenticated // TODO: of User
let context = React.createContext(Guest)
module Provider = {
let make = React.Context.provider(context)
}
What’s the recommended way of doing auth in rescript? Is there any examples of it?
Could you show a simplified version of how you would make it in JS?
I’d erm… just use react query with something like this, but that’s very different from what I can do on rescript, I imagine? In that case, I’m setting the context to undefined, passing functions in objects, everything I wouldn’t do on rescript.
import React, { createContext, useContext } from 'react';
import { useMutation } from '@tanstack/react-query';
const AuthContext = createContext(undefined);
export function AuthProvider({ children }) {
const { mutateAsync: login, data: user, error, isPending } = useMutation({
mutationFn: (credentials) => Fetch.authenticateUser(credentials),
});
const value = { user, login, error, isPending };
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
}
export function useAuth() {
const context = useContext(AuthContext);
if (context === undefined) {
throw new Error('useAuth must be used within an AuthProvider');
}
return context;
}
Edit: The code was generated by claude because it’s a simple example.
Yeah that looks pretty straightforward to me, all of this can be easily done in rescript, where’s the blocker exactly? Did you try writing bindings for this?
No, because I have like, no I dont know how can I do that on rescript.
That js implementation depends a lot on react query, so I don’t know if I can do anything like it either
There seems to be some rescript bindings for react query already, I don’t know how up to date they are but it’s likely a good base!
Kinda still lost though, maybe I’m just lost on rescript itself.
Will need to read more then, thx.