useReducer:
const [post, dispatch] = React.useReducer(AddPostReducer, {
description: "",
location: "",
photos: []
});
При нажатии на submit:
React.useEffect(() => {
if (!post.photos.length) return;
dispatchRed(addPostAsyncAction(post, setErrors, setText));
navigate("/");
}, [post.photos]);
function uploadPhotos(event: React.ChangeEvent<HTMLFormElement>) {
event.preventDefault();
if (!selectedImages.length) return;
dispatch({ type: "SET_PHOTOS", payload: { selectedImages, setText } });
}
Reducer:
case SET_PHOTOS:
const { selectedImages, setText } = action.payload;
const formData = new FormData();
selectedImages.map((image: any) => formData.append("photos", image));
uploadPhotos(formData)
.then((data) => {
const { success, message, fileNames } = data;
if (!success) {
setText(message);
return;
}
return {
...state,
photos: fileNames
};
});
return state;
uploadPhotos:
function uploadPhotos(formData: any) {
return trackPromise(fetch(`${REACT_APP_API_URL}/upload/photos`, {
method: "POST",
headers: {
"Accept-Type": "application/json",
Authorization: `Bearer ${Cookies.get("token") || ""}`,
},
body: formData
})
.then((response) => response.json())
.then((data) => data));
}
Error:
MainLayout
- главный компонент для обертки.
AddPost
- страница, на которой происходит ошибка