Search code examples
reactjstypescript

Setting variable which is key-value pairs via setState


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 should I do?


Solution

  • Use primitive types (string, number) instead of built-in types (String, Number).

    Also, you should define the type in useState as below:

    const [data, setData] = useState<{
       files: [];
       processed_files: number;
       URL: string;
    } | null>(null);
    
    socket.on("send_data", function (...response: any) {
        setData({ files: response[0], processed_files: 0, URL: "" });
    });