I have 3 dropzones, each one accepts a different file. I want to have a submit button that will submit all the files that have been uploaded.
How do I write out that function?
I want it to have a handleSubmit function.
These are my state variables for the different files:
const [csvFile, setCsvFile] = React.useState();
const [emailFile, setEmailFile] = React.useState();
const [domainFile, setDomainFile] = React.useState();
const handleSubmit = async (file) => {
const allFiles = [csvFile, emailFile, domainFile];
setDisabled(true);
if (!listId) {
await Promise.all(
allFiles.map((file_) => {
console.log({ file });
const formData = {
name: _.get(file, 'meta.name', ''),
};
return dispatch(createListAction(formData))
.then((response) => {
const listIdentifier = _.get(response, 'data.id');
uploadList({ csvFile, emailFile, domainFile }, listIdentifier);
})
.catch((error) => {
toast((t) => <Toast toastId={t} error={error} />, { duration: Infinity });
console.log({ error });
});
}),
);
} else {
allFiles.forEach((file_) => {
uploadList(file, listId);
});
}
};
At the moment when I press the submit button 3 files upload even though only 1 was uploaded, I am not sure why 3 are uploading? Any ideas?
Related
I have a simple notes app, where I made it possible for adding, deleting a single note and changing importance. But I can't figure out how to make it moving single note up or down; change the order of notes. My approach is to reorder array of current notes and then somehow post or replace existing collection in my database. But I can't find right tool for this.
I'm using React, Node.js and MongoDB through Mongoose.
P.S: I googled it, and found nothing relevant to this. But I think it's a simple operation and there should be a function for this in MongoDB.
Here is code from my backend index.js file:
app.post('/api/notes', (request, response) => {
const body = request.body;
if (body.content === undefined) {
return response.status(400).json({
error: 'content missing',
});
}
const note = new Note({
content: body.content,
important: body.important || false,
date: new Date(),
});
note.save().then((savedNote) => {
response.json(savedNote);
});
});
app.get('/api/notes/', (request, response) => {
Note.find({}).then((notes) => {
response.json(notes);
});
});
app.get('/api/notes/:id', (request, response, next) => {
Note.findById(request.params.id)
.then((note) => {
if (note) {
response.json(note);
} else {
response.status(404).end();
}
})
.catch((error) => next(error));
});
app.delete('/api/notes/:id', (request, response, next) => {
Note.findByIdAndRemove(request.params.id)
.then((result) => {
response.status(204).end();
})
.catch((error) => next(error));
});
app.put('/api/notes/:id', (request, response, next) => {
const body = request.body;
const note = {
content: body.content,
important: body.important,
};
Note.findByIdAndUpdate(request.params.id, note, { new: true })
.then((updatedNote) => {
response.json(updatedNote);
})
.catch((error) => next(error));
});
Code snippet from frontend:
const App = () => {
const [notes, setNotes] = useState([]);
const [newNote, setNewNote] = useState('');
const [showAll, setShowAll] = useState(true);
const [errorMessage, setErrorMessage] = useState(null);
useEffect(() => {
noteService.getAll().then((initialNotes) => {
setNotes(initialNotes);
});
}, []);
const addNote = (event) => {
event.preventDefault();
const noteObject = {
content: newNote,
date: new Date().toISOString(),
important: Math.random() > 0.5,
id: notes.length + 1,
};
noteService.create(noteObject).then((returnedNote) => {
setNotes(notes.concat(returnedNote));
setNewNote('');
});
};
const handleNoteChange = (event) => {
setNewNote(event.target.value);
};
const toggleImportanceOf = (id) => {
const note = notes.find((n) => n.id === id);
const changedNote = { ...note, important: !note.important };
console.log('Changed');
noteService
.update(id, changedNote)
.then((returnedNote) => {
console.log(returnedNote);
setNotes(notes.map((note) => (note.id !== id ? note : returnedNote)));
})
.catch((error) => {
setErrorMessage(
`Note '${note.content}' was already removed from server`
);
setTimeout(() => {
setErrorMessage(null);
}, 5000);
setNotes(notes.filter((n) => n.id !== id));
});
};
const delNote = (id) => {
window.confirm(`Delete this note?`);
noteService.del(id);
noteService.getAll().then((initialNotes) => {
setNotes(initialNotes);
});
};
const moveUp = (id) => {
const idN = notes.findIndex((n) => n.id === id);
console.log(idN);
//that's where I reorder my current notes(moving up)
let updated = [...notes];
updated.splice(
idN === 0 ? updated.length - 1 : idN - 1,
0,
updated.splice(idN, 1)[0]
);
};
const notesToShow = showAll ? notes : notes.filter((note) => note.important);
And finally code from api (noteService in the code above):
const getAll = () => {
let request = axios.get(baseUrl);
return request.then((res) => res.data);
};
const create = (newObject) => {
const request = axios.post(baseUrl, newObject);
return request.then((res) => res.data);
};
const update = (id, newObject) => {
const request = axios.put(`${baseUrl}/${id}`, newObject);
return request.then((res) => res.data);
};
const del = (id) => {
axios.delete(`${baseUrl}/${id}`);
};
Is there a way to delete all uploaded files at once? When I uploaded success. I want to call event remove all files. I didn't find any solution for this. Tks for all the help !
Here is my code:
upload file
const [fileDatas, setFileDatas] = useState([]);
const dummyRequest = ({ file, onSuccess }) => {};
const beforeUpload = (file, fileList) => {return false};
const { Dragger } = Upload;
const props = {
accept: 'image/png, image/jpeg, image/svg, image/gif, .xlsx,.xls,image/*,.doc, .docx,.ppt, .pptx,.txt,.pdf',
name: 'file',
multiple: true,
beforeUpload: beforeUpload,
action: dummyRequest,
onChange({ file, fileList }) {
if (file.status !== 'uploading') {
setFileUploads(fileList);
}
},
onDrop(e) {
console.log('Dropped files', e.dataTransfer.files);
setFileUploads(e.dataTransfer.files);
},
};
handle event submit upload file
const handleUploadFile = () => {
if (fileUploads.length === 0) {
toastActionWarning('No files to upload');
}else{
setFileUploads([]);
const formDatas = new FormData();
fileUploads.forEach((file) => {
formDatas.append(file.name, file.originFileObj);
});
axios
.post('files', formDatas, { withCredentials: true })
.then((res) => {
let newList = [...fileDatas];
res.data.data.forEach(element => {
element.author = window.userDisplayName;
newList = [element, ...newList]
});
setFileDatas(newList);
//I want to clear all file here
toastActionSuccess('Upload successfully');
})
.catch((error) => {
toastActionFailed('There was an error in processing');
});
}
};
i'm not sure what i'm doing wrong here, i upload a new picture to firebase storage, then i retrieve it with getDownloadUrl, and then i update the user profile photoURL, but for some reason it's not working.
const imgPath = ref(storage, "images/");
const imgUpload = () => {
if (uImg == null) return;
const imgRef = ref(storage, `images/${uImg.name + v4()}`);
uploadBytes(imgRef, uImg).then(() => {
listAll(imgPath).then((response) => {
response.items.forEach((item) => {
getDownloadURL(item).then((url) => {
setImgUrl([url]);
updateProfile(auth.currentUser, {
photoURL: `${imgUrl[0]}`,
})
.then(() => {
setProfileImg(auth.currentUser.photoURL);
console.log("success");
})
.catch((error) => {
console.log(error);
});
});
});
});
});
};
uImg is the uploaded img
It is unlikely the current user is updated by the time the updateProfile then statement runs.
Instead update the useState hook as with the imgUrl[0].
updateProfile(auth.currentUser, { photoURL: `${imgUrl[0]}` })
.then(() => {
setProfileImg(imgUrl[0]);
console.log("success");
}).catch((error) => { console.log(error); });
If you want to verify that the profile image was updated print of the value:
const auth = getAuth();
useEffect(() => {
console.log("Profile:", auth.currentUser?.photoURL);
}, []);
I've managed to establish a connection using socket. It works great for the first few seconds after that it runs super slow takes like almost 2-3 mins to complete a request. And then it produces this error continuously. The app doesn't crash it just runs slowly with the error displaying countless times.
Firefox can’t establish a connection to the server at ws://localhost:5000/socket.io/?EIO=4&transport=websocket&sid=9S6kqHJdHHXQgrobAAHp..
Error on console.
Main.js
function Home(props) {
const [Username , setUsername] = useState("")
const [SearchedData, setSearchedData] = useState()
const [Data, setData] = useState()
const socket = io('http://localhost:5000')
React.useEffect(() => {
// socket.current = io('http://localhost:5000')
socket.emit("content","yada")
socket.on("get-data", data => {
setData(data)
})
})
function NavBar(props){
const handleClick = (e) => {
const {id} = e.target
if(id === "Post-btn"){
if(Content.length > 0){
let data = {
Username: "yada", Content
}
props.socket.emit("store-data", data)
}
}
return(
Tags....
)}
function Content (props) {
const onLike = (e) => {
const { id } = e.target.dataset
const data = {
username: "yada",
id : id
}
// console.log(data)
props.socket.emit("like", data)
}
return(
Tags.....
)
}
server.js
mongoose.connect(process.env.MongoDB,
{ useNewUrlParser: true, useUnifiedTopology: true }).then(() => {
console.log("Database Connected")
}).catch(err => {
console.log(err)
});
const server = app.listen(process.env.Port, () => {
console.log("Connected on " + process.env.Port)
})
const io = socket(server, {
cors:{
origin: "http://localhost:3000",
credential: true,
}
})
let cuid;
io.on("connection", (socket) => {
socket.on("content", username => {
Comments.find({},(err, data) => {
if(!err)
socket.emit("get-data", data)
})
})
socket.on("store-data", data => {
const {Username, Content} = data
const newdata = new Comments({
userName: Username,
content: Content,
createdAt: new Date().toDateString(),
replies: []
})
newdata.save().then(data => {
for(const d in data)
if(d === "_id"){
Users.findOneAndUpdate({username: Username}, {$push: {UserContent: data[d]}}, {new: true}, (err, save) => {
if(err)
console.log(err)
else
console.log(save)
})
}
})
})
socket.on("like", data => {
const {username, id} = data
Users.findOne({username:username}, (err, data) => {
if(!err){
cuid = data['id']
console.log(cuid)
Comments.findByIdAndUpdate(id, {$set: {score: data['_id']}}, {upsert: true}, (err, d) => {
if(!err){
console.log(d)
}
})
}
})
})
})
Looking at the code provided, I noticed there is an useEffect without params. This may be causing a loop until the application crashes.
React.useEffect(() => {
// socket.current = io('http://localhost:5000')
socket.emit("content","yada")
socket.on("get-data", data => {
setData(data)
})
socket.on("Updated", data => {
setData(data)
})
}, []); <- this is missing
This empty array indicates that the content inside the useEffect will only run once.
More about this https://reactjs.org/docs/hooks-intro.html
below is my main code for my project, which is a simple open chatting room.
This is a chatting client basically, which can only get chatting logs and post chats.
To log in, I request for an authorization key to the server and use that key to start chatting.
The thing that I want to do is to get the chatting logs from the server every 3 seconds.
So, after it retrieves chats every 3 seconds, the page should refresh with new chats.
However, this seems not to be working well for me.
If there is a good React pro who can solve this problem for me, please do.
import React from 'react';
import { withRouter } from 'react-router-dom';
import './Chat.css';
import InfoBar from '../InfoBar/InfoBar';
import Input from '../Input/Input';
import Messages from '../Messages/Messages';
const API_ENDPOINT = 'https://snu-web-random-chat.herokuapp.com';
let INTERVAL_ID;
const Chat = ({ token, setToken }) => {
const [ name, setName ] = React.useState('');
const [ message, setMessage ] = React.useState('');
const [ messages, setMessages ] = React.useState([]);
const [ lastEl, setLastEl ] = React.useState({});
React.useEffect(() => {
if (localStorage.getItem('username')) {
setName(localStorage.getItem('username'));
}
window.addEventListener('scroll', listenToScroll, true);
fetchData();
INTERVAL_ID = setInterval(() => {
fetchData();
}, 3000);
return () => {
window.removeEventListener('scroll', listenToScroll);
clearInterval(INTERVAL_ID);
};
}, []);
const fetchData = () => {
fetch(`${API_ENDPOINT}/chats?createdAtFrom=${lastEl.createdAt || ''}`)
.then((res) => res.json())
.then((msgs) => {
const updatedMsgs = messages.concat(msgs);
setLastEl(msgs[msgs.length - 1]);
setMessages(updatedMsgs);
});
};
const listenToScroll = (e) => {
const div = document.getElementById('messagesContainer');
// console.log(window.scrollY);
// const winScroll = document.body.scrollTop || document.documentElement.scrollTop;
// const height = document.documentElement.scrollHeight - document.documentElement.clientHeight;
// const scrolled = winScroll / height;
};
const onLogin = (e) => {
e.preventDefault();
fetch(`${API_ENDPOINT}/login`, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: `name=${name}`
})
.then((response) => response.json())
.then(({ key }) => {
if (key) {
setToken(true);
localStorage.setItem('__key', key);
localStorage.setItem('username', name);
}
})
.catch((err) => console.error(err));
};
const sendMessage = (e) => {
e.preventDefault();
if (message) {
fetch(`${API_ENDPOINT}/chats`, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
Authorization: `Key ${localStorage.getItem('__key')}`
},
body: `message=${message}`
})
.then((response) => response.json())
.then((res) => {
const obj = {
createdAt: res.createdAt,
message: res.message,
userName: res.user.name,
_id: res.user._id
};
setMessages([ ...messages, obj ]);
})
.catch((err) => console.error(err));
setMessage('');
}
};
const logout = () => {
localStorage.removeItem('__key');
localStorage.removeItem('username');
setToken(false);
};
const loadMessages = () => {
fetchData();
clearInterval(INTERVAL_ID);
};
return (
<div className="outerContainer">
<div className="innerContainer">
<InfoBar
name={name}
token={token}
handleInput={(e) => setName(e.target.value)}
handleLogin={onLogin}
handleLogout={logout}
/>
<Messages messages={messages} name={name} lastEl={lastEl} loadMore={loadMessages} />
{token && <Input message={message} setMessage={setMessage} sendMessage={sendMessage} />}
</div>
</div>
);
};
export default withRouter(Chat);
I can give u the advice to make a chat app with socket.io, not setInterval.
https://socket.io/get-started/chat