How to implemet useMutation from react-query in handleSubmit - javascript

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.com/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);
}
}

Something 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.com/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 component
const uploadImage = async file => {
const url = `https://api.cloudinary.com/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

Related

Unable to Map Array of MongoDB Documents Returned from Backend into React Components

I am trying to get my front-end to call to the back-end for all the "blog posts" that are stored in my MongoDB database. At the moment there is only one document for testing.
On the backend I have this api endpoint:
app.get("/api/blogs", async (req, res) => {
console.log("Getting blog items...");
try{
const blogs = await blogActions.getBlogItems();
res.status(200).json({blogs});
} catch (err) {
console.log(err)
}
});
This calls to a separate JS file with this function:
const { MongoClient } = require('mongodb');
const uri = 'mongodb://localhost:27017';
const client = new MongoClient(uri);
const connection = async () => {
try {
const database = client.db('personalwebsite');
const blogs = database.collection('blogs');
return blogs;
} catch (err) {
console.log(err);
}
}
const getBlogItems = async () => {
const conn = await connection();
try {
return await conn.find({}).toArray();
} catch (err) {
console.log(err);
}
};
Then in my React front-end I am trying to take the returned array and set it to an Array there in order to map over it and create a new BlogItem component for each blog returned from the database:
import { useState, useEffect } from "react";
import Navbar from "../components/Navbar.tsx";
import BlogItem from "../components/BlogItem.tsx";
import '../styles/Blog.css';
export default function Blog () {
const [isLoggedIn, setIsLoggedIn] = useState<boolean>(false);
const [isAdmin, setIsAdmin] = useState<boolean>(false);
const [token, setToken] = useState<string>('');
const [blogs, setBlogs] = useState([]);
useEffect(() => {
setToken(localStorage.getItem('token'));
async function checkToken () {
const response = await fetch('/api/token', {
method: 'POST',
headers: {
'Content-type': 'application/json',
'Authorization': `Bearer ${token}`
}
});
if (response.ok){
const jsonResponse = await response.json();
if (jsonResponse.delete){
localStorage.clear();
return false;
}
return true;
} else {
console.log("Failed to fetch status of the User Login Session.");
}
}
async function checkIfAdmin () {
const response = await fetch('/api/users/permissions', {
method: 'POST',
headers: {
'Content-type': 'application/json',
'Authorization': `Bearer ${token}`
}
});
if(response.ok) {
const jsonResponse = await response.json();
if (jsonResponse.role === 'admin') {
setIsAdmin(true);
} else {
setIsAdmin(false);
}
}
}
async function getBlogItems () {
try {
const response = await fetch('/api/blogs');
const data = await response.json();
console.log("Before setBlogs", data.blogs)
if(data.blogs.length > 0) {
setBlogs(data.blogs);
}
} catch (err) {
console.log(err);
}
}
if (token) {
checkToken().then(isValid => {
if (!isValid) return;
checkIfAdmin();
});
}
getBlogItems();
}, [])
console.log("After setBlogs", blogs);
return (
<div className="App">
<Navbar />
<main className="main-content">
<div className="blogs-container">
{blogs.length > 0 ? (
blogs.map((blog) => (
<BlogItem
key={blog._id}
title={blog.title}
shortDesc={blog.shortDesc}
imgSrc={blog.imgSrc}
pubDate={blog.pubDate}
/>
))
) : (
<div>Loading...</div>
)}
</div>
<div className="most-popular"></div>
</main>
</div>
);
}
I have tried quite a few different methods for trying to get this to work correctly. At first I thought it was just a problem with the data not being returned quickly enough but even after getting the code to wait for the data to be returned and getting the Array to set. I get an error that Objects are not valid as a React child.
This is meant to be an array of Objects so that I can access the properties of each object for the elements in the component but I cannot get it to work for the life of me. I spent awhile using ChatGPT to try and get some progress out of it but this seems to be a problem that requires human intervention instead.
So this is annoying but the issue wasn't with the rest of my code but actually that the BlogItem component had the props wrapped only in parentheses.
Here is the component:
export default function BlogItem ({title, shortDesc, imgSrc, pubDate}) {
return (
<div className="blog-item">
<img src={imgSrc} className="blog-image" />
<h1 className="blog-title">{title === "" ? "Placeholder Title" : title }</h1>
<p className="blog-short-desc">{shortDesc}</p>
<p className="blog-date">{pubDate}</p>
</div>
);
}
The fix was that title, shortDesc, imgSrc, pubDate. All needed to be wrapped in Curly Braces. It now works :\

Javascript react safe image in database

I have a problem with saving pictures in the database. I want to do a post Method, where i can safe a file in a directory and save the picture link in the database.
Here is my Code:
`const toBase64 = file => new Promise((resolve, reject) => {
const reader = new FileReader()
reader.readAsDataURL(file)
reader.onload = () => resolve(reader.result)
reader.onerror = error => reject(error)
})`
` const [base64Image, setBase64Image] = useState("")
const [imagePath, setImagePath] = useState("")
const fileInput = useRef(null)`
`const onFileInputChange = async (e) => {
const file = fileInput.current.files[0]
if (!file) return
const base64 = await toBase64(file)
setBase64Image(base64)}`
` const handleSubmitImage = async (e) => {
e.preventDefault()
if (!base64Image) return
const response = await fetch("/public", {
method: "POST",
headers: {
"content-type": "application/json"
},
body: JSON.stringify(base64Image)
})
const data = await response.json()
setImagePath(data.filePath)
}`
Post:
`const handleSubmit = async (e) => {
e.preventDefault()
setIsLoading(true)
setErrors(defaultModel)
const result = validateModel(post)
if (!result.isValid) {
setErrors(result.errors)
setIsLoading(false)
return
}
if (post.id) {
await updatePost(post, session.accessToken)
alert("Post updated!")
router.push(`/posts/${post.id}`)
} else {
const newPost = await createPost(post, session.accessToken)
alert("Post created!")
router.push(`/posts/${newPost.id}`)
}
setIsLoading(false)
}
`
` <fieldset onSubmit={handleSubmitImage} className={styles.form}>
<p>Image:</p>
<input value={post.image}
type="file"
accept=".png,.jpg"
ref={fileInput}
onChange={onFileInputChange}
/>
{/* eslint-disable-next-line #next/next/no-img-element */}
{base64Image && <img src={base64Image} style={{width: "1000px", height: "1000px"}} alt={""}/>}
{imagePath && <p>
<Link href={`http://localhost:3000${imagePath}`}
passHref><a>http://localhost:3000{imagePath}</a></Link>
</p>
}
</fieldset>`
Right now i can connect to the Explorer and pick an Image. I can also display the image. If i press on create, it doesnt work properly with saving the image in the database.

Uncaught ReferenceError: keyword is not defined at UseFetch.jsx and at Transactions.jsx

I am trying to load a website to my localhost but keep running into an error that says Uncaught ReferenceError: keyword is not defined at useFetch (:3000/src/hooks/useFetch.jsx:21:7) at TransactionsCard (:3000/src/components/Transactions.jsx:33:18). The issue hapens in my code where I'm fetching gifs from my API at giphy developer.
Here is the source code:
Transactions.jsx:
import React, { useEffect, useState } from "react";
import { ethers } from "ethers";
import { contractABI, contractAddress } from "../utils/constants";
export const TransactionContext = React.createContext();
const { ethereum } = window;
const createEthereumContract = () => {
const provider = new ethers.providers.Web3Provider(ethereum);
const signer = provider.getSigner();
const transactionsContract = new ethers.Contract(contractAddress, contractABI, signer);
return transactionsContract;
};
export const TransactionsProvider = ({ children }) => {
const [formData, setformData] = useState({ addressTo: "", amount: "", keyword: "", message: "" });
const [currentAccount, setCurrentAccount] = useState("");
const [isLoading, setIsLoading] = useState(false);
const [transactionCount, setTransactionCount] = useState(localStorage.getItem("transactionCount"));
const [transactions, setTransactions] = useState([]);
const handleChange = (e, name) => {
setformData((prevState) => ({ ...prevState, [name]: e.target.value }));
};
const getAllTransactions = async () => {
try {
if (ethereum) {
const transactionsContract = createEthereumContract();
const availableTransactions = await transactionsContract.getAllTransactions();
const structuredTransactions = availableTransactions.map((transaction) => ({
addressTo: transaction.receiver,
addressFrom: transaction.sender,
timestamp: new Date(transaction.timestamp.toNumber() * 1000).toLocaleString(),
message: transaction.message,
keyword: transaction.keyword,
amount: parseInt(transaction.amount._hex) / (10 ** 18)
}));
console.log(structuredTransactions);
setTransactions(structuredTransactions);
} else {
console.log("Ethereum is not present");
}
} catch (error) {
console.log(error);
}
};
const checkIfWalletIsConnect = async () => {
try {
if (!ethereum) return alert("Please install MetaMask.");
const accounts = await ethereum.request({ method: "eth_accounts" });
if (accounts.length) {
setCurrentAccount(accounts[0]);
getAllTransactions();
} else {
console.log("No accounts found");
}
} catch (error) {
console.log(error);
}
};
const checkIfTransactionsExists = async () => {
try {
if (ethereum) {
const transactionsContract = createEthereumContract();
const currentTransactionCount = await transactionsContract.getTransactionCount();
window.localStorage.setItem("transactionCount", currentTransactionCount);
}
} catch (error) {
console.log(error);
throw new Error("No ethereum object");
}
};
const connectWallet = async () => {
try {
if (!ethereum) return alert("Please install MetaMask.");
const accounts = await ethereum.request({ method: "eth_requestAccounts", });
setCurrentAccount(accounts[0]);
window.location.reload();
} catch (error) {
console.log(error);
throw new Error("No ethereum object");
}
};
const sendTransaction = async () => {
try {
if (ethereum) {
const { addressTo, amount, keyword, message } = formData;
const transactionsContract = createEthereumContract();
const parsedAmount = ethers.utils.parseEther(amount);
await ethereum.request({
method: "eth_sendTransaction",
params: [{
from: currentAccount,
to: addressTo,
gas: "0x5208", //21,000 gwei in hexadecimal form
value: parsedAmount._hex,
}],
});
const transactionHash = await transactionsContract.addToBlockchain(addressTo, parsedAmount, message, keyword);
setIsLoading(true);
console.log(`Loading - ${transactionHash.hash}`);
await transactionHash.wait();
console.log(`Success - ${transactionHash.hash}`);
setIsLoading(false);
const transactionsCount = await transactionsContract.getTransactionCount();
setTransactionCount(transactionsCount.toNumber());
window.location.reload();
} else {
console.log("No ethereum object");
}
} catch (error) {
console.log(error);
throw new Error("No ethereum object");
}
};
useEffect(() => {
checkIfWalletIsConnect();
checkIfTransactionsExists();
}, [transactionCount]);
return (
<TransactionContext.Provider
value={{
transactionCount,
connectWallet,
transactions,
currentAccount,
isLoading,
sendTransaction,
handleChange,
formData,
}}
>
{children}
</TransactionContext.Provider>
);
};
useFetch.jsx:
import { useEffect, useState } from 'react';
const API_KEY = import.meta.env.VITE_GIPHY_API;
const useFetch = () => {
const [gifUrl, setGifUrl] = useState("");
const fetchGifs = async () => {
try {
const response = await fetch(`https://api.giphy.com/v1/gifs/search?api_key=${API_KEY}&q=${keyword.split(" ").join("")}&limit=1`)
const { data } = await response.json();
setGifUrl(data[0]?.images?.downsized_medium?.url)
} catch (error) {
setGifUrl('https://metro.co.uk/wp-content/uploads/2015/05/pokemon_crying.gif?quality=90&strip=all&zoom=1&resize=500%2C284')
}
}
useEffect(() => {
if (keyword) fetchGifs();
}, [keyword]);
return gifUrl;
}
export default useFetch;
When I comment out the lines that use 'keyword' it launches with no errors. This is at lines 14, 18, and 58-62 of Transactions.jsx.
Any help would be greatly appreciated, thank you!
The problem here is that you have not define keyword inside your useFetch function.
If you are trying to pass the keyword from the place where you use useFetch then do something like below and use the useFetch like const gifUrl = useFetch(<keyword>)
import { useEffect, useState } from 'react';
const API_KEY = import.meta.env.VITE_GIPHY_API;
const useFetch = (keyword) => {
const [gifUrl, setGifUrl] = useState("");
const fetchGifs = async () => {
try {
const response = await fetch(`https://api.giphy.com/v1/gifs/search?api_key=${API_KEY}&q=${keyword.split(" ").join("")}&limit=1`)
const { data } = await response.json();
setGifUrl(data[0]?.images?.downsized_medium?.url)
} catch (error) {
setGifUrl('https://metro.co.uk/wp-content/uploads/2015/05/pokemon_crying.gif?quality=90&strip=all&zoom=1&resize=500%2C284')
}
}
useEffect(() => {
if (keyword) fetchGifs();
}, [keyword]);
return gifUrl;
}
export default useFetch;
or even try adding default value for key work like below.
const useFetch = (keyword = "some keyword") => {

How do convert a datauri element into a file I can upload via react?

I am sending a file to an api endpoint via react webapp and for now as a mock up have been using file upload. I have since added camera capabilities as I plan for users to be able to take a picture and upload that picture. I'm using the react-html5-camera-photo which captures a datauri element. How do I convert this to a file to upload to the endpoint? Or am I approaching this incorrectly?
File Upload:
handleUploadImage=()=> {
console.log(this.state.selectedFile)
const data = new FormData();
data.append('file', this.state.selectedFile);
data.append('filename', this.state.selectedFile.name);
fetch('http://localhost:5000/upload', {
method: 'POST',
body: data,
})
.then((response) => {
response.json()
.then((response) => {
//this.setState({ imageURL: `http://localhost:5000/${body.file}` });
console.log(response.text)
this.setState({ text: response.text})
this.getPlate()
})
});
}
Camera Code:
startCamera = () => {
console.log('starting camera')
if(!this.state.cameraLoad) {
this.setState({ cameraLoad: true, camIconData: collapse}) ;
} else {
this.setState({ cameraLoad: false, camIconData: expand}) ;
}
}
onTakePhoto = (dataUri) => {
// Do stuff with the dataUri photo...
console.log('photo taken');
this.setState({ camColor: 'green', dataUri : dataUri })
}
// will upload photo after user confirms to upload
uploadPhoto = e => {
console.log('uploading photo')
console.log(this.state.dataUri)
this.setState({ camColor: 'green', dataUri: null, cameraLoad: false });
};
The dataUri element looks something like:
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABQAAAALQCAYAAADPfd1WAAAgAElEQVR4XlS9h5Nk63HdmeVdV5vpmXnzDAEQBAiKwlJmIzZiQ/u/72qDWongkpREQFjRgHh2/LQp7zd+52TeavSLfjPTXXXr3s/kl3n
Here is the complete example. Please write a CameraComponent as below where you will find submitPhoto() function and this function is responsible for uploading image to the api.
import React, {useState} from 'react';
import Camera from 'react-html5-camera-photo';
import 'react-html5-camera-photo/build/css/index.css';
import ImagePreview from "./ImagePreview";
import axios from 'axios';
function CameraComponent(props) {
const [dataUri, setDataUri] = useState('');
const isFullscreen = false;
const cameraRef = React.useRef();
function handleTakePhoto(dataUri) {
console.log('takePhoto');
}
function handleTakePhotoAnimationDone(dataUri) {
console.log(dataUri, 'takePhoto');
setDataUri(dataUri);
}
function handleCameraError(error) {
console.log('handleCameraError', error);
}
function handleCameraStart(stream) {
console.log('handleCameraStart');
}
function handleCameraStop() {
console.log('handleCameraStop');
}
function submitPhoto() {
const url = "http://localhost:3000/api/img";
const request = axios.post(url, {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify({
img: dataUri
})
}).catch(error => {
console.warn(error);
});
}
return (
<div>
<button onClick={submitPhoto}>Upload</button>
{(dataUri)
? <ImagePreview dataUri={dataUri}
isFullscreen={isFullscreen}
/> :
<Camera ref={cameraRef}
onTakePhoto={(dataUri) => {
handleTakePhoto(dataUri);
}}
onTakePhotoAnimationDone={(dataUri) => {
handleTakePhotoAnimationDone(dataUri);
}}
onCameraError={(error) => {
handleCameraError(error);
}}
onCameraStart={(stream) => {
handleCameraStart(stream);
}}
onCameraStop={() => {
handleCameraStop();
}}
/>
}
</div>
);
}
export default CameraComponent;
Here is the another component ImagePreview which will preview the image
import React from 'react';
import PropTypes from 'prop-types';
import './styles/imagePreview.css';
export const ImagePreview = ({ dataUri, isFullscreen }) => {
let classNameFullscreen = isFullscreen ? 'demo-image-preview-fullscreen' : '';
return (
<div className={'demo-image-preview ' + classNameFullscreen}>
<img src={dataUri} />
</div>
);
};
ImagePreview.propTypes = {
dataUri: PropTypes.string,
isFullscreen: PropTypes.bool
};
export default ImagePreview;
use this :
function dataURLtoFile(dataurl, filename) {
var arr = dataurl.split(","),
mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]),
n = bstr.length,
u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new File([u8arr], filename, { type: mime });
}
var convertedFile = dataURLtoFile(dataUri, `${Math.random(10)}.jpg`);

How to make direct api call to cloudinary with axios?

I am trying to figure this out with axios. I have made the direct api call with superagent and now want to know how to use with axios as the rest of my project is with axios. I know there is cloudinary-react, but this is the way I prefer to do it.
Here is what I have so far.
import React, { Component } from 'react';
import Dropzone from 'react-dropzone';
import sha1 from 'sha1';
import superagent from 'superagent';
import axios from 'axios';
class Images extends Component {
uploadFile(files) {
console.log('uploadFile: ');
const image = files[0];
const cloudName = 'tbaustin';
const url = `https://api.cloudinary.com/v1_1/${cloudName}/image/upload`;
const timestamp = Date.now()/1000;
const uploadPreset = 'cnh7rzwp';
const paramsStr = `timestamp=${timestamp}&upload_preset=${uploadPreset}secret`;
const signature = sha1(paramsStr);
const params = {
'api_key': 'api_key',
'timestamp': timestamp,
'upload_preset': uploadPreset,
'signature': signature
}
let uploadRequest = superagent.post(url)
uploadRequest.attach('file', image);
Object.keys(params).forEach((key) => {
uploadRequest.field(key, params[key]);
});
uploadRequest.end((err, res) => {
if(err) {
alert(err);
return
}
console.log('UPLOAD COMLETE: '+JSON.stringify(res.body));
});
//AXIOS CONTENT HERE
// let request = axios.post(url, {file: image});
// request.then((response) => {
// Object.keys(params).forEach((key) => {
// uploadRequest.field(key, params[key]);
// });
// console.log('UPLOAD COMPLETE: '+JSON.stringify(response.body));
// }).catch((err) => { alert(err); });
}
render() {
return (
<div>
<Dropzone onDrop={this.uploadFile.bind(this)}/>
</div>
)
}
}
export default Images;
This worked for me.
let formData = new FormData();
formData.append("api_key",'');
formData.append("file", image);
formData.append("public_id", "sample_image");
formData.append("timestamp", timeStamp);
formData.append("upload_preset", uploadPreset);
axios
.post(url, formData)
.then((result) => {
console.log(result);
})
.catch((err) => {
console.log(err);
})
This is a part of my project when I tried to upload an avatar. I have set my upload preset to unsigned on cloudinary.
const uploadPhotoHandler = async (e) => {
const file = e.target.files[0];
const formData = new FormData();
formData.append("file", file);
formData.append("upload_preset", "pa*****");
try {
setPictureProfile("./assets/img/giphy.gif");
const res = await axios.post("https://api.cloudinary.com/v1_1/${cloud_name}/upload", formData);
console.log(res.data.url);
setPictureProfile(res.data.url);
} catch (error) {}
};

Categories

Resources