Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adds functionality to upload photo #69

Merged
merged 7 commits into from
Jun 15, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 0 additions & 7 deletions src/components/App/App.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import { useDispatch, useSelector } from "react-redux";
import { refreshUser } from "../../redux/auth/operations";
import { selectIsRefreshing } from "../../redux/auth/selectors";


import RestrictedRoute from "../RestrictedRoute/RestrictedRoute";
import PrivateRoute from "../PrivateRoute/PrivateRoute";

Expand All @@ -17,18 +16,12 @@ const NotFoundPage = lazy(() => import("../../pages/NotFoundPage"));

export const App = () => {
const isRefreshing = useSelector(selectIsRefreshing);
// const isLoggedIn = useSelector(selectIsLoggedIn);
const dispatch = useDispatch();

useEffect(() => {
dispatch(refreshUser());
}, [dispatch]);

// useEffect(() => {
// if (isLoggedIn) {
// dispatch(getUserInfo());
// }
// }, [dispatch, isLoggedIn]);
return (
<>
{isRefreshing ? (
Expand Down
5 changes: 5 additions & 0 deletions src/components/Header/Header.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,11 @@ export default function Header({ openSideBar, sideBarOpen }) {
// style={{
// backgroundImage: `url(${user.avatarURL})`,
// }}
style={
user.avatarURL
? { backgroundImage: `url(${user.avatarURL})` }
: {}
}
/>
</button>
</div>
Expand Down
1 change: 0 additions & 1 deletion src/components/Header/Header.module.css
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,6 @@

@media screen and (min-width: 1440px) {
.container {
/* min-width: 1440px; */
margin-right: 0;
}
.headerLayout {
Expand Down
74 changes: 45 additions & 29 deletions src/components/UserEditModal/UserEditModal.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import { Field, Form, Formik } from "formik";
import { ErrorMessage } from "formik";
import PasswordField from "../PasswordField/PasswordField";
import { updateUserInfo } from "../../redux/auth/operations";
import { updAvatarURL } from "../../redux/auth/slice";
import axios from "axios";
import * as Yup from "yup";
import css from "../UserEditModal/UserEditModal.module.css";
import svg from "../../img/icons.svg";
Expand All @@ -26,24 +28,9 @@ export default function UserEditModal({ onClose }) {
const user = useSelector(selectUser);
const dispatch = useDispatch();

// ссылка к скрытому тнпуту тип файл
const fileInputRef = useRef(null);

const handleSubmit = async (values) => {
console.log(values);
try {
const sendInfo = {
avatarURL: values.avatarURL,
name: values.name,
email: values.email,
password: values.password,
};
await dispatch(updateUserInfo(sendInfo)).unwrap();
// отправляем операцию aпдейтюзера и передаем ей обьект с данными имя мыло пароль
} catch (error) {
console.log(error);
}
};

const handleMenuClick = (ev) => {
ev.stopPropagation();
};
Expand All @@ -52,11 +39,44 @@ export default function UserEditModal({ onClose }) {
fileInputRef.current.click();
};

const handleFileChange = (event) => {
const handleFileChange = async (event) => {
const file = event.target.files[0];
if (file) {
console.log("Selected file:", file.name);
// добавить логику для загрузки файла на сервер или обновления аватара
try {
//создаем новый объект FormData для отправки файла на сервер
const formData = new FormData();
//добавляем выбранный файл в объект FormData
formData.append("avatar", file);
const response = await axios.put(
"https://project06back.onrender.com/current/avatar",
formData,
{
headers: {
"Content-Type": "multipart/form-data",
},
}
);
const url = response.data.avatarURL;
if (url) {
// Установ новый URL аватара в стейт пользователя
dispatch(updAvatarURL(url));
}
} catch (error) {
console.log(error);
}
}
};

const handleSubmit = async (values) => {
try {
const sendInfo = {
name: values.name,
email: values.email,
password: values.password,
};
await dispatch(updateUserInfo(sendInfo)).unwrap();
} catch (error) {
console.log(error);
}
};

Expand All @@ -78,9 +98,11 @@ export default function UserEditModal({ onClose }) {
<div className={css.avatarContainer}>
<span
className={`${css.avatarBig} ${css.avatar}`}
// style={{
// backgroundImage: `url(${user.avatarURL})`,
// }}
style={
user.avatarURL
? { backgroundImage: `url(${user.avatarURL})` }
: {}
}
/>

<button
Expand All @@ -102,7 +124,7 @@ export default function UserEditModal({ onClose }) {
<div>
<Formik
initialValues={{
// avatarURL: user.avatarURL || null,
avatarURL: user.avatarURL || "",
name: user.name || "",
email: user.email || "",
password: "",
Expand All @@ -111,12 +133,6 @@ export default function UserEditModal({ onClose }) {
validationSchema={ValidationSchema}
>
<Form className={css.forma} autoComplete="off">
{/* <Field
type="text"
name="avatarURL"
className={css.formInput}
placeholder="avatar"
/> */}
<div className={css.formGroup}>
<label htmlFor="name" className={css.formLabel} />
<Field
Expand Down
4 changes: 2 additions & 2 deletions src/components/UserEditModal/UserEditModal.module.css
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@

.plusBtn {
border: none;
background-color: #bedbb0;
background-color: var(--green);
border-radius: 4px;
width: 24px;
height: 24px;
Expand Down Expand Up @@ -153,7 +153,7 @@
display: block;
cursor: pointer;
border-radius: 5px;
background-image: url(/src/img/deftAvBlack.png);
background-image: url(https://res.cloudinary.com/dqwyuuuzd/image/upload/v1718235453/pojpj365oqqbots9321l.png);
background-repeat: no-repeat;
background-position: center;
background-size: cover;
Expand Down
26 changes: 2 additions & 24 deletions src/redux/auth/operations.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
// import { createAction } from "@reduxjs/toolkit";
import axios from "axios";
import { createAsyncThunk } from "@reduxjs/toolkit";

Expand Down Expand Up @@ -71,37 +72,14 @@ export const refreshUser = createAsyncThunk(
}
);

/*
* GET @ /
* headers: Authorization: Bearer token
*/

// export const getUserInfo = createAsyncThunk(
// "user/getUserInfo",
// async (_, thunkAPI) => {
// try {
// const response = await axios.get("/current");
// return response.data;
// } catch (error) {
// return thunkAPI.rejectWithValue(error.message);
// }
// }
// );

/*
* Put @ /
* headers: Authorization: Bearer token
* body: {name, email, password }
*/
export const updateUserInfo = createAsyncThunk(
"user/updateUserInfo",
async (userData, thunkAPI) => {
try {
console.log(userData);
const reduxState = thunkAPI.getState();
const savedToken = reduxState.auth.token;
setAuthHeader(savedToken);
const response = await axios.put("/current", userData);
const response = await axios.patch("/current/update", userData);
return response.data;
} catch (error) {
return thunkAPI.rejectWithValue(error.message);
Expand Down
31 changes: 10 additions & 21 deletions src/redux/auth/slice.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import {
logOut,
register,
updateUserInfo,
// getUserInfo,
refreshUser,
} from "./operations";

Expand All @@ -23,6 +22,11 @@ const authSlice = createSlice({
loading: false,
error: false,
},
reducers: {
updAvatarURL(state, action) {
state.user.avatarURL = action.payload;
},
},
extraReducers: (builder) =>
builder
.addCase(register.pending, (state) => {
Expand Down Expand Up @@ -67,23 +71,6 @@ const authSlice = createSlice({
state.loading = false;
state.error = true;
})
// .addCase(getUserInfo.pending, (state) => {
// state.loading = true;
// state.error = false;
// })
// .addCase(getUserInfo.fulfilled, (state, action) => {
// state.loading = false;
// // state.user = action.payload;
// state.user.name = action.payload.name;
// state.user.email = action.payload.email;
// state.user.theme = action.payload.theme;
// state.user.avatarURL = action.payload.avatarURL;
// state.isLoggedIn = true;
// })
// .addCase(getUserInfo.rejected, (state, action) => {
// state.loading = false;
// state.error = action.payload;
// })
.addCase(updateUserInfo.pending, (state) => {
state.loading = true;
state.error = false;
Expand All @@ -108,9 +95,10 @@ const authSlice = createSlice({
state.error = true;
})
.addCase(refreshUser.fulfilled, (state, action) => {
// action.payload.avatarURL =
// "https://cdn.britannica.com/26/162626-050-3534626F/Koala.jpg";
state.user = action.payload;
state.user.name = action.payload.name;
state.user.email = action.payload.email;
state.user.avatarURL = action.payload.avatarURL;
state.user.theme = action.payload.theme;
state.isLoggedIn = true;
state.isRefreshing = false;
})
Expand All @@ -121,3 +109,4 @@ const authSlice = createSlice({
}),
});
export const authReducer = authSlice.reducer;
export const { updAvatarURL } = authSlice.actions;