How to access React useContext outside a component?

723 Views Asked by At

I have all my api functions in a special folder. When I use them, I sometimes have to update the context, which stores the user's informations.

However, the app crashes when I try to access its value directly from within these functions. So I always have to import the context in the component, and then pass the function setUser as a parameter to the api function. It is a bit messy. How to properly access and update the context's state in my api service?

Here is a classic function:

export async function useUpdatePassword(
  email: string,
  password: string,
  token
) {
  const { setUser } = useUser();
  try {
    const res = await ax.post(process.env.SERVER_URL + "/update-password", {
      email,
      password,
      token,
    });
    localStorage.setItem("myapp", res.data.token);
    setUser(jwt_decode(res.data.token));
    return "update password done!!"
  } catch (err) {
    return "error"
  }
}

And my context:

const UserContext = createContext(null);

export default function UserProvider({ children }) {
  const [user, setUser] = useState<User>();

  useEffect(() => {
    fetchUser(setUser); // fetch user infos in my db
  }, []);

  return (
    <UserContext.Provider value={{ user, setUser }}>
      {children}
    </UserContext.Provider>
  );
}

export function useUser() {
  return useContext(UserContext);
}

If there is no way to do it with Context, is it possible to use Redux, Jotai or any other library to do so?

0

There are 0 best solutions below