admin管理员组文章数量:1384622
I tried to rewrite this Submit function to use react query useMutation but i get errors.Does somebody know how to change this to be writen with useMutation.I thank you very much for every hint and every answer to this question.
async function handleSubmit(e) {
e.preventDefault();
try {
if (file) {
// if file is set send it to cloudinary api
const url = `/${CLOUD_NAME}/upload`;
loading(true);
const formData = new FormData();
formData.append("file", file);
formData.append("upload_preset", UPLOAD_PRESET);
const res = await fetch(url, {
method: "POST",
body: formData,
});
// get data and pull out 1000w image url
const data = await res.json();
const fileUrl = await data.eager[0].secure_url;
console.log(fileUrl);
setError("");
if (album.trim() !== "" && color.trim() !== "" && fileUrl) {
// Craeting Date form
const albumData = new FormData();
albumData.append("name", album);
albumData.append("bckImgUrl", fileUrl);
albumData.append("color", color);
// change albumData to json
const object = {};
albumData.forEach((value, key) => (object[key] = value));
// sending data to /api/v1/albums
const res = await fetch(`${SERVER_API}/api/v1/albums`, {
method: "POST",
body: JSON.stringify(object),
headers: {
"Content-Type": "application/json",
},
});
if (!res.ok) {
const message = `An error has occured: ${res.status}`;
setError(message);
}
const data = await res.json();
const id = await data.data._id;
loading(false);
history.push(`/albums/${id}`);
} else {
setError("Please enter all the field values.");
}
} else {
setError("Please select a file to add.");
}
} catch (error) {
error.response && setError(error.response.data);
}
}
I tried to rewrite this Submit function to use react query useMutation but i get errors.Does somebody know how to change this to be writen with useMutation.I thank you very much for every hint and every answer to this question.
async function handleSubmit(e) {
e.preventDefault();
try {
if (file) {
// if file is set send it to cloudinary api
const url = `https://api.cloudinary./v1_1/${CLOUD_NAME}/upload`;
loading(true);
const formData = new FormData();
formData.append("file", file);
formData.append("upload_preset", UPLOAD_PRESET);
const res = await fetch(url, {
method: "POST",
body: formData,
});
// get data and pull out 1000w image url
const data = await res.json();
const fileUrl = await data.eager[0].secure_url;
console.log(fileUrl);
setError("");
if (album.trim() !== "" && color.trim() !== "" && fileUrl) {
// Craeting Date form
const albumData = new FormData();
albumData.append("name", album);
albumData.append("bckImgUrl", fileUrl);
albumData.append("color", color);
// change albumData to json
const object = {};
albumData.forEach((value, key) => (object[key] = value));
// sending data to /api/v1/albums
const res = await fetch(`${SERVER_API}/api/v1/albums`, {
method: "POST",
body: JSON.stringify(object),
headers: {
"Content-Type": "application/json",
},
});
if (!res.ok) {
const message = `An error has occured: ${res.status}`;
setError(message);
}
const data = await res.json();
const id = await data.data._id;
loading(false);
history.push(`/albums/${id}`);
} else {
setError("Please enter all the field values.");
}
} else {
setError("Please select a file to add.");
}
} catch (error) {
error.response && setError(error.response.data);
}
}
Share
Improve this question
asked Dec 21, 2020 at 20:33
klixoklixo
4522 gold badges8 silver badges19 bronze badges
3
- check this, There is description how upload files with useMutation – Robert Commented Dec 21, 2020 at 20:39
- @Robert the code i post is working but i dont know how to change it with useMutation this is the problem – klixo Commented Dec 21, 2020 at 20:43
- chat.stackoverflow./rooms/226261/usemutation-with-kuba here we can speak a little – Robert Commented Dec 21, 2020 at 20:56
2 Answers
Reset to default 2Something like that. As simple as possible
Codesandbox link for demo
import { Fragment, useState } from "react";
import axios from "axios";
import { useMutation } from "react-query";
const senRequest = async () => {
return await axios.get("https://jsonplaceholder.typicode./posts");
};
export default function App() {
const [val, setVal] = useState("");
const [result, setResult] = useState([]);
const { mutate } = useMutation(senRequest); // if you need to send data configure it from here
const handleSubmit = (e) => {
e.preventDefault();
mutate(senRequest, { // And send it in here.
onSuccess: ({ data }) => {
setResult(data.slice(0, 5));
}
});
};
return (
<div className="App">
<form onSubmit={handleSubmit}>
<input value={val} onChange={(e) => setVal(e.target.value)} />
<button type="submit">Submit</button>
</form>
{result.map((el) => (
<Fragment key={el.id}>
<div
style={{
width: "100%",
borderBottom: "1px solid gray"
}}
>
<span>{el.title}</span>
<span>{el.body}</span>
</div>
</Fragment>
))}
</div>
);
}
little refactor suggestion :)
import React from "react";
import { useHistory } from "react-router-dom";
import { UPLOAD_PRESET, CLOUD_NAME, SERVER_API } from "../../config";
// to don't redefine this function on each rerender they can be defined out of ponent
const uploadImage = async file => {
const url = `https://api.cloudinary./v1_1/${CLOUD_NAME}/upload`;
const formData = new FormData();
formData.append("file", file);
formData.append("upload_preset", UPLOAD_PRESET);
const res = await fetch(url, {
method: "POST",
body: formData,
});
if (!res.ok) {
throw new Error(`Can't upload image. ${res.status}`)
}
const data = await res.json();
return await data.eager[0].secure_url;
}
const createAlbum = async data => {
const res = await fetch(`${SERVER_API}/api/v1/albums`, {
method: "POST",
body: JSON.stringify(data),
headers: {
"Content-Type": "application/json",
},
});
if (!res.ok) {
throw new Error(`An error has occurred: ${res.status}`)
}
const json = await res.json();
return json.data._id;
}
const Form = ({ file, loading: setLoading, setError, album, color, children }) => {
let history = useHistory();
const clearError = () => setError("")
const handleSubmit = async e => {
e.preventDefault();
clearError();
try {
if (!file) {
throw new Error("Please select a file to add.");
}
if (!album.trim() || !color.trim()){
throw new Error("Please enter all the field values.");
}
setLoading(true);
const fileUrl = await uploadImage(file);
const data = {
"name": album,
"bckImgUrl": fileUrl,
"color": color
};
const albumId = await createAlbum(data);
history.push(`/albums/${albumId}`);
} catch (error) {
setError(error.message);
} finally {
setLoading(false)
}
}
return <form onSubmit={handleSubmit}>{children}</form>
}
export default Form
本文标签: javascriptHow to implemet useMutation from reactquery in handleSubmitStack Overflow
版权声明:本文标题:javascript - How to implemet useMutation from react-query in handleSubmit - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744512303a2609955.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论