'How to specify the image type in typescript?
How to specify the fileSelect's type in typescript ? I'm refactoring my code to typescript but there is Error in useState and formData.append("file", fileSelect)'s type error
so this is part of my code and
const [fileSelect, setFileSelect] = useState<File | null>(null);
this has type error
import React from "react";
import wellcome from "../char-image/welcome.png";
import chat from "../char-image/chat.png";
import { useState, useRef, useEffect } from "react";
import UserAndBlock from "./UserAndBlock";
import { messageType } from '../App'
import { eType } from '../App'
import { blockListType } from '../App'
import { chatingPageProps } from '../page/ChatingPage'
let getImage: File | null = null;
let chatTyping: boolean = false;
function Chatroom({
ws,
fetchChatList,
isUserName,
isUserId,
onChat,
setOnchat,
openUserList,
typingM,
leaveChat,
openHandler,
enterMsg,
setOpenUserList,
blockList,
setBlockList,
setWs,
}: chatingPageProps) {
const messageRef = useRef<HTMLDivElement>(null);
const [fileSelect, setFileSelect] = useState<File | null>(null);
const [isFile, setIsFile] = useState<boolean>(false);
const [fileSend, setFileSend] = useState<boolean>(false);
const [sendMessage, setSendMessage] = useState<string>("");
const [isUserList, setIsUserList] = useState<messageType[]>([]);
const filterdMessage = enterMsg.filter((msg: messageType) => {
return !blockList.some((bl: blockListType) => {
return msg.idx === bl.target;
});
});
const cancelImage = () => {
getImage = null;
setIsFile(false);
setFileSend(false);
};
const handlePost = async () => {
const formData = new FormData();
formData.append("file", fileSelect);
return fetch(`http://localhost:8443/upload?file=${isFile}`, {
method: "POST",
body: formData,
headers: {
"Content-Type": "multipart/form-data",
},
})
.then((res) => res.json())
.then((res) => {
getImage = res;
sendImage();
});
};
const sendImage = () => {
if (getImage) {
ws.send(
JSON.stringify({
event: "message",
message: getImage.upload,
})
);
}
ws.onmessage = function () {
fetchChatList();
};
scrollToBottom();
setFileSelect(null);
setIsFile(false);
setFileSend(false);
};
this code to upload file but I dont know what type is that
const [fileSelect, setFileSelect] = useState<File | null>(null);
const handlePost = async () => {
const formData = new FormData();
formData.append("file", fileSelect);// fileSelect has error
//"Argument of type 'File | null' is not
// assignable to parameter of type 'string | Blob'.
// Type 'null' is not assignable to type 'string | Blob'"
return fetch(`http://localhost:8443/upload?file=${isFile}`, {
method: "POST",
body: formData,
headers: {
"Content-Type": "multipart/form-data",
},
})
.then((res) => res.json())
.then((res) => {
getImage = res;
sendImage();
});
};
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
