https://github.com/sohanemon/with-firebase
https://github.com/sohanemon/with-firebase
context-api firebase firebase-auth private-routes react react-hook-form react-router
Last synced: about 2 months ago
JSON representation
- Host: GitHub
- URL: https://github.com/sohanemon/with-firebase
- Owner: sohanemon
- Created: 2022-10-20T10:17:57.000Z (over 3 years ago)
- Default Branch: master
- Last Pushed: 2022-10-20T16:25:09.000Z (over 3 years ago)
- Last Synced: 2025-03-05T01:41:55.020Z (about 1 year ago)
- Topics: context-api, firebase, firebase-auth, private-routes, react, react-hook-form, react-router
- Language: JavaScript
- Homepage: https://with-firebase.netlify.app
- Size: 434 KB
- Stars: 1
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# [react-hook-form](https://react-hook-form.com/)
## Basics
- register input with `register('email')` function
- inject the output from register in input. ``
- pass the `handleSubmit` function from `useForm()`
```js
console.log(data))}>...
```
and avoid this
```js
handleSubmit(callback)}>...
```
- inside the `form` there should be at least a button or type='submit'
## Intermediate (validation)
- `register()` takes two params. First is name and second one is options which is optional. [show more](./src/assets/Screenshot_1.png)
- ` {...register("email", { required: "Email is required" })}` this required field will return as a message.
- find the error at `const {formState : {errors}} = useForm()`
# _Private_ Route using [React router](https://reactrouter.com)
## Basic
- create a component that returns it's children on condition.
```js
const PrivateRoute = ({ children }) => {
if (user?.uid) return children;
return <>Loading...>;
};
export default PrivateRoute;
```
- now wrap any component with `PrivateRoute`
```js
{
path: "/",
element: (
),
},
```
## Intermediate
- Go to different page if condition doesn't full fill
```js
const PrivateRoute = ({ children }) => {
if (user?.uid) return children;
return ;
};
```
- use `Navigate` component instead of `useNavigate()` hook there.
```js
const PrivateRoute = ({ children }) => {
const navigate = useNavigate();
const { user } = useContext(User);
if (user?.uid) return children;
else navigate("/signin");
};
```
> `useNavigate` works on events only
## Redirect to previous path after private route
- navigate with state & replace
```js
//private route.jsx
const PrivateRoute = ({ children }) => {
const { pathname } = useLocation();
if (user?.uid) return children;
return ;
// navigated from pathname
// passing a props named state
};
```
> state props will be injected to the location of `/login`
- get the pathname
```js
// login.jsx
const {
state: { pathname },
} = useLocation();
// location.state.pathname // state={{ pathname }}
```
- now we know the previous location and go with
```js
//login.jsx
setTimeout(() => navigate(pathname || '/'), 100);
// go to root route if pathname not available
```