T
TanStack17mo ago
frozen-sapphire

How to return (useMutation) correctly in (Context API)?

In the first picture, I created a custom React hook for useMutation. Then I obtained the type of useMutation by hovering over the title of my function to use that type in the Context API. In the second picture, I placed the type of my useSignUp/useMutation in the Context, but for the default value of the Context, I don't know what to put there. What I want to happen is to call the signUp function from the Context API like this:
const { signUp } = useSession()

signUp.mutate(values)
const { signUp } = useSession()

signUp.mutate(values)
No description
No description
4 Replies
genetic-orange
genetic-orange16mo ago
It seems like you don't have your head fully wrapped around these things and are trying to make a non-trivial abstraction, so for starters I would recommend to start very simply with minimal abstractions and then break out things into contexts etc. when it makes sense. More concretely, I don't see why you would want your custom mutation hook in your context. The hook can be exported as a standalone function, and will work just fine. Anyhow, I think that is only the first of several issues you will run into, so I really want to recommend trying to do one small step at a time and get that working before moving on.
frozen-sapphire
frozen-sapphireOP16mo ago
I want the sign-up mutation and the log-in mutation, as well as my session that comes from my backend server, to be in a single file, so I created a session provider.
foreign-sapphire
foreign-sapphire16mo ago
Your problem is the initialContext. It doesn't really make sense to initialise it like that in this case. You could instead assume that it's an error if the context has not been provided properly. E.g
type AuthContextProps = {
...
}

const AuthContext = createContext<AuthContextProps | null>(null);

export const useAuth = () => {
const context = useContext(AuthContext);

if (!context) {
throw new Error("useAuth() must be used within an AuthContext");
}

return context;
};
type AuthContextProps = {
...
}

const AuthContext = createContext<AuthContextProps | null>(null);

export const useAuth = () => {
const context = useContext(AuthContext);

if (!context) {
throw new Error("useAuth() must be used within an AuthContext");
}

return context;
};
This way you don't need to provide any "mock" function for signUp
frozen-sapphire
frozen-sapphireOP16mo ago
thank you sir

Did you find this page helpful?