Skip to content

Commit

Permalink
edição de usuario
Browse files Browse the repository at this point in the history
  • Loading branch information
matheusbattisti committed Apr 3, 2022
1 parent 68a76d9 commit d41974e
Show file tree
Hide file tree
Showing 17 changed files with 180 additions and 55 deletions.
2 changes: 1 addition & 1 deletion 13_REACTGRAM/backend/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ app.use(express.urlencoded({ extended: false }));
app.use(cors({ credentials: true, origin: "http://localhost:3000" }));

// Upload directory
app.use(express.static(path.join(__dirname, "uploads")));
app.use("/uploads", express.static(path.join(__dirname, "/uploads")));

// db connection
require("./config/db.js");
Expand Down
2 changes: 1 addition & 1 deletion 13_REACTGRAM/backend/controllers/UserController.js
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ const update = async (req, res) => {

const reqUser = req.user;

const user = await User.findById(reqUser._id);
const user = await User.findById(reqUser._id).select("-password");

if (name) {
user.name = name;
Expand Down
5 changes: 5 additions & 0 deletions 13_REACTGRAM/frontend/src/App.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import Home from "./pages/Home/Home";
import Login from "./pages/Auth/Login";
import Register from "./pages/Auth/Register";
import Profile from "./pages/Profile/Profile";
import MyPhotos from "./pages/MyPhotos/MyPhotos";

function App() {
const { auth, loading } = useAuth();
Expand All @@ -37,6 +38,10 @@ function App() {
path="/profile"
element={auth ? <Profile /> : <Navigate to="/login" />}
/>
<Route
path="/myphotos"
element={auth ? <MyPhotos /> : <Navigate to="/login" />}
/>
<Route
path="login"
element={!auth ? <Login /> : <Navigate to="/" />}
Expand Down
14 changes: 0 additions & 14 deletions 13_REACTGRAM/frontend/src/components/ErrorMessage.js

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,12 +1,22 @@
.error {
.message {
border-radius: 5px;
padding: 5px 10px;
color: #721c24;
background-color: #f8d7da;
border-color: #f5c6cb;
position: relative;
margin: 0;
display: flex;
justify-content: center;
align-items: center;
}

.error {

color: #721c24;
background-color: #f8d7da;
border-color: #f5c6cb;
}

.success {
color: #155724;
background-color: #d4edda;
border-color: #c3e6cb;
}
13 changes: 13 additions & 0 deletions 13_REACTGRAM/frontend/src/components/Message.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import "./Message.css";

import { BsXLg } from "react-icons/bs";

const Message = ({ msg, type }) => {
return (
<div className={`message ${type}`}>
<p>{msg}</p>
</div>
);
};

export default Message;
12 changes: 11 additions & 1 deletion 13_REACTGRAM/frontend/src/components/Navbar.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,12 @@ import "./Navbar.css";

// Components
import { NavLink, Link } from "react-router-dom";
import { BsSearch, BsHouseDoorFill, BsFillPersonFill } from "react-icons/bs";
import {
BsSearch,
BsHouseDoorFill,
BsFillPersonFill,
BsFillCameraFill,
} from "react-icons/bs";

// Hooks
import { useAuth } from "../hooks/useAuth";
Expand Down Expand Up @@ -38,6 +43,11 @@ const Navbar = () => {
<BsHouseDoorFill />
</NavLink>
</li>
<li>
<NavLink to="/myphotos">
<BsFillCameraFill />
</NavLink>
</li>
<li>
<NavLink to="/profile">
<BsFillPersonFill />
Expand Down
13 changes: 13 additions & 0 deletions 13_REACTGRAM/frontend/src/index.css
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,19 @@ form {
flex-direction: column;
}

label {
display: flex;
flex-direction: column;
text-align: left;
}

label span {
font-weight: bold;
margin-bottom: .5em;
color: #AAA;
font-size: .7em;
}

input {
background-color: #3b3b3b;
color: #aaa;
Expand Down
4 changes: 2 additions & 2 deletions 13_REACTGRAM/frontend/src/pages/Auth/Login.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import "./Auth.css";

// Components
import { Link } from "react-router-dom";
import ErrorMessage from "../../components/ErrorMessage";
import ErrorMessage from "../../components/Message";

// Hooks
import { useEffect, useState } from "react";
Expand Down Expand Up @@ -56,7 +56,7 @@ const Login = () => {
/>
{!loading && <input type="submit" value="Entrar" />}
{loading && <input type="submit" disabled value="Aguarde..." />}
{error && <ErrorMessage error={error} />}
{error && <ErrorMessage error={error} type={error} />}
</form>
<p>
Não tem uma conta? <Link to="/register">Clique aqui</Link>
Expand Down
4 changes: 2 additions & 2 deletions 13_REACTGRAM/frontend/src/pages/Auth/Register.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import "./Auth.css";

// Components
import { Link } from "react-router-dom";
import ErrorMessage from "../../components/ErrorMessage";
import ErrorMessage from "../../components/Message";

// Hooks
import { useState, useEffect } from "react";
Expand Down Expand Up @@ -72,7 +72,7 @@ const Register = () => {
/>
{!loading && <input type="submit" value="Cadastrar" />}
{loading && <input type="submit" disabled value="Aguarde..." />}
{error && <ErrorMessage error={error} />}
{error && <ErrorMessage error={error} type={error} />}
</form>
<p>
Já tem conta? <Link to="/login">Clique aqui</Link>
Expand Down
Empty file.
7 changes: 7 additions & 0 deletions 13_REACTGRAM/frontend/src/pages/MyPhotos/MyPhotos.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import "./MyPhotos.css";

const MyPhotos = () => {
return <div>MyPhotos</div>;
};

export default MyPhotos;
7 changes: 7 additions & 0 deletions 13_REACTGRAM/frontend/src/pages/Profile/Profile.css
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,10 @@
.subtitle {
color: #ccc;
}

.profile-image {
width: 150px;
height: 150px;
border-radius: 50%;
margin-bottom: 1em;
}
77 changes: 61 additions & 16 deletions 13_REACTGRAM/frontend/src/pages/Profile/Profile.js
Original file line number Diff line number Diff line change
@@ -1,22 +1,28 @@
import "./Profile.css";

import { uploads } from "../../utils/config";

// Hooks
import { useEffect, useState } from "react";
import { useSelector, useDispatch } from "react-redux";

// Redux
import { profile, updateProfile } from "../../slices/userSlice";
import { profile, updateProfile, resetMessage } from "../../slices/userSlice";

// Components
import Message from "../../components/Message";

const Profile = () => {
const dispatch = useDispatch();

const { user, loading } = useSelector((state) => state.user);
const { user, loading, message, error } = useSelector((state) => state.user);

const [name, setName] = useState("");
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [profileImage, setImageProfile] = useState("");
const [profileImage, setProfileImage] = useState("");
const [bio, setBio] = useState("");
const [previewImage, setPreviewImage] = useState("");

// Load user data
useEffect(() => {
Expand All @@ -32,7 +38,7 @@ const Profile = () => {
}
}, [user]);

const handleSubmit = (e) => {
const handleSubmit = async (e) => {
e.preventDefault();

// Gather user data from states
Expand All @@ -48,21 +54,52 @@ const Profile = () => {
userData.bio = bio;
}

dispatch(updateProfile(userData));
console.log(profileImage);
console.log(userData);

// build form data
const formData = new FormData();

const userFormData = Object.keys(userData).forEach((key) =>
formData.append(key, userData[key])
);

formData.append("user", userFormData);

await dispatch(updateProfile(formData));

setTimeout(() => {
dispatch(resetMessage());
}, 2000);
};

const handleFile = () => {};
const handleFile = (e) => {
// image preview
const image = e.target.files[0];

if (loading) {
return <p>Carregando...</p>;
}
setPreviewImage(image);

// change image state
setProfileImage(image);
};

return (
<div id="profile">
<h2>Edite seus dados</h2>
<p className="subtitle">
Adicione uma imagem de perfil, e conte mais um pouco sobre você...
</p>
{(user.profileImage || previewImage) && (
<img
className="profile-image"
src={
previewImage
? URL.createObjectURL(previewImage)
: `${uploads}/users/${user.profileImage}`
}
alt={user.name}
/>
)}
<form onSubmit={handleSubmit}>
<input
type="text"
Expand All @@ -71,14 +108,22 @@ const Profile = () => {
value={name || ""}
/>
<input type="email" placeholder="E-mail" disabled value={email || ""} />
<input type="file" onChange={handleFile} />
<input
type="text"
placeholder="Descrição do perfil"
onChange={(e) => setBio(e.target.value)}
value={bio || ""}
/>
<label>
<span>Imagem de Perfil:</span>
<input type="file" onChange={handleFile} />
</label>
<label>
<span>Bio:</span>
<input
type="text"
placeholder="Descrição do perfil"
onChange={(e) => setBio(e.target.value)}
value={bio || ""}
/>
</label>
<input type="submit" value="Atualizar" />
{error && <Message msg={error} type="error" />}
{message && <Message msg={message} type="success" />}
</form>
</div>
);
Expand Down
5 changes: 4 additions & 1 deletion 13_REACTGRAM/frontend/src/services/userService.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,10 @@ const profile = async (data, token) => {

// Update user details
const updateProfile = async (data, token) => {
const config = requestConfig("PUT", data, token);
const config = requestConfig("PUT", data, token, true);

console.log(config);
console.log(data);

try {
const res = await fetch(api + "/users/", config)
Expand Down
25 changes: 20 additions & 5 deletions 13_REACTGRAM/frontend/src/slices/userSlice.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ const initialState = {
error: false,
success: false,
loading: false,
message: null,
};

// Get user details
Expand Down Expand Up @@ -45,10 +46,8 @@ export const userSlice = createSlice({
name: "user",
initialState,
reducers: {
reset: (state) => {
state.loading = false;
state.error = false;
state.success = false;
resetMessage: (state) => {
state.message = null;
},
},
extraReducers: (builder) => {
Expand All @@ -62,9 +61,25 @@ export const userSlice = createSlice({
state.success = true;
state.error = null;
state.user = action.payload;
})
.addCase(updateProfile.pending, (state) => {
state.loading = true;
state.error = null;
})
.addCase(updateProfile.fulfilled, (state, action) => {
state.loading = false;
state.success = true;
state.error = null;
state.user = action.payload;
state.message = "Usuário atualizado com sucesso!";
})
.addCase(updateProfile.rejected, (state, action) => {
state.loading = false;
state.error = action.payload;
state.user = null;
});
},
});

export const { reset } = userSlice.actions;
export const { resetMessage } = userSlice.actions;
export default userSlice.reducer;
Loading

0 comments on commit d41974e

Please sign in to comment.