hey need some help with react typescript
here I define a variable, data
const [data, setData] = useState({
files: [],
processed_files: Number,
URL: String,
});
logging data
works fine:
(3) [{…}, {…}, {…}]
0: {files: Array(2)}
1: {processed_files: 0}
2: {url: 'f179d744-cdfb-4546-b756-afb6d5daaeff'}
length:3
[[Prototype]]:Array(0)
I try to use setData in this way:
socket.on("send_data", function (...response: any) {
setData(response)
});
but further logging the keys in the dictionary says it is undefined:
useEffect(() => {
console.log(data); //this works fine (image uploaded)
console.log(data.files); //undefined
console.log(data.processed_files); //undefined
console.log(data.url); //undefined
}, [data]);
I then try this but it causes errors
socket.on("send_data", function (...response: any) {
setData({files : response[0], processed_files : 0 as Number, URL : "" as String});
});
Type 'Number' is missing the following properties from type 'NumberConstructor': prototype, MAX_VALUE, MIN_VALUE, NaN, and 11 more. ts(2740)
Type 'String' is missing the following properties from type 'StringConstructor': prototype, fromCharCode, fromCodePoint, raw ts(2739)
what do I do?
2
Answers
I have found out the issue, I solved it using an interface
fixed the console log showing undefined like so:
I should have also mentioned how i got my data (mb)
Use primitive types (
string
,number
) instead of built-in types (String
,Number
).Also, you should define the type in
useState
as below: