-
Notifications
You must be signed in to change notification settings - Fork 18
Getting Started
For this app, we'll assume that backend is done for us, and we'll just be using react-cookie to set cookies.
First, we'll import react-cookie with import { useCookies } from "react-cookie";
. You can also use script tags:
<script
crossorigin
src="https://unpkg.com/universal-cookie@3/umd/universalCookie.min.js"
></script>
<script
crossorigin
src="https://unpkg.com/react-cookie@3/umd/reactCookie.min.js"
></script>
Next, let's initialize our variables:
import { useCookies } from "react-cookie";
const [cookies, setCookie, removeCookie] = useCookies(["token"]);
Let's take a peek into this destructured hook:
- The
cookies
variable is a JSON object with all your cookies -
setCookie
allows you to set a cookie -
removeCookie
allows you to remove a cookie - Inside the
useCookies()
function, we're declaring the name of the cookie.
We'll use the setCookie()
function to set our cookies:
// pages/blog/#.jsx
export default function Login(newUserToken) {
return (
<button onClick={() => setCookie("token", newUserToken)}>Login!</button>
)
}
Great! Now we set cookies whenever a user triggers our login function. But, there's a problem, it's only working on pages in the /blog
path! Let's dig into our options and set the path to "/"
// pages/blog/#.jsx
export default function Login(newUserToken) {
return (
<button onClick={() => setCookie("token", newUserToken, {path: "/"})}>Login!</button>
)
}
Now, I want to allow my users to view and delete their token. Let's first add a way to allow the user to view their cookie using the cookies
object.
// pages/blog/#.jsx
export default function Login(newUserToken) {
return (
<>
<button onClick={() => setCookie("token", newUserToken, {path: "/"})}>Login!</button>
<p> See your cookie: {cookies.token}</p>
</>
)
}
Now, that's add a button to allow a user to delete their cookie:
// pages/blog/#.jsx
export default function Login(newUserToken) {
return (
<>
<button onClick={() => setCookie("token", newUserToken, {path: "/"})}>Login!</button>
<p> See your cookie: {cookies.token}</p>
<button onClick={() => removeCookie("token", {path: "/"})}>Login!</button>
</>
)
}
Congrats! You've just made your first app! Check out our other documentation.