skip to Main Content

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


  1. Chosen as BEST ANSWER

    I have found out the issue, I solved it using an interface

    interface serverData{
        files: Array<string>,
        processed_files: number,
        URL: string
    }
    
    const [data, setData] = useState<serverData>({
            files: [],
            processed_files: 0,
            URL: "",
        });
    
    

    fixed the console log showing undefined like so:

    socket.on("send_data", function (...response: any) {
            setData({files : response[0]['files'], processed_files: response[1]['processed_files'] , URL : response[2]['url'] });
        });
    

    I should have also mentioned how i got my data (mb)

        socketio.emit('send_data', ({"files": files}, {"processed_files": processed_files}, {"url": url}))
    

  2. 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: "" });
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search