Get Current User
2021 May 20th
This is one way I log in a user in React JS.
1const handleSubmit = async () => {2 const response = await fetch(`${API_URL}/auth/login`, {3 method: "POST",4 mode: "cors",5 headers: { "Content-Type": "application/json" },6 body: JSON.stringify({ email: `${email}`, password: `${password}` }),7 });89 if (response.ok) {10 console.log("Login failed")11 } else {12 }13 const res = await response.json();14 if (res.auth_token !== undefined) {15 window.localStorage.setItem("auth_token", res.auth_token);16 window.location.reload();17 }18};
& how I get that user.
1ct(() => {2 const getCurrentUser = async () => {3 const token = window.localStorage.getItem("auth_token");4 const response = await fetch(`${API_URL}/users/token`, {5 method: "GET",6 mode: "cors",7 headers: { Authorization: `Bearer ${token}` },8 });9 if (!response.ok) {10 console.log("get current user failed");11 } else {12 const json = await response.json();13 setCurrentUser(json);14 }15 };16 getCurrentUser();17}, []);