Search code examples
reactjstypescriptreact-state-management

Shorten multiple lines of setState code in react


This question is just for the purpose of improving my codes in React which currently looks very dirty and unreadable. I have 10-15 forms field which updated once I get values from APIs.

Here is the code from which I did this,

            this.setState({smtpServer:res.data.data[0].smtpServer});
            this.setState({senderName:res.data.data[0].senderName});
            this.setState({senderEmail:res.data.data[0].senderEmail});
            this.setState({smtpPorts:res.data.data[0].smtpPort});
            this.setState({username:res.data.data[0].username});
            this.setState({password:res.data.data[0].password});
            this.setState({authType:res.data.data[0].authType});

There is also lots more of setState method which I didn't add. This makes my component code complex. Is there any method to shorten these codes.


Solution

  • You can shorten them by fitting it all into a single object state using setState. First try to destructure your res.data.data[0] object in order to handle the individual attributes better:

    const { smptServer, 
            senderName, 
            senderEmail, 
            smtpPort,
            username, 
            password, 
            authType} = res.data.data[0];
    

    Next you can set state in one GIANT OBJECT with each attributes. ES6 allows javascript to use key only instead of key-value pairs when the key and value have the same name. Thus: const objName = {username:username, password:password} can also be typed as const objName = {username,password} By that logic you can just setState as:

    this.setState({ smptServer, 
            senderName, 
            senderEmail, 
            smtpPort,
            username, 
            password, 
            authType});
    

    Hope this helps.