DEV Community

Discussion on: On immutability and sanity

Collapse
 
misterwhat profile image
Jonas Winzen

Why do you use an extra variable to hold the date string? You can do the conversion at the place, where it's needed, like this: <td>{moment(transaction.date).format('DD/MM/YYYY')}</td>
?
Using an extra variable makes sense, when the computation of the result is performance intense or being used at several places.
Alternatively you could have used object destructuring assignment in the arguments, to avoid mutating the original object:

.map( ( {amount, date, client}, i ) => {
        date = moment(date).format('DD/MM/YYYY')
        return (
            <tr key={i}>
                <td>{amount}</td>
                <td>{date}</td>
                <td>{client}</td>
            </tr>
    })

This is not only shorter to write, it also gives you the opportunity to default missing values (e.g. ({someValue = "example default value"}) => ...) and a convenient way to rename keys, very useful to keep .map() an understandable one liner: e.g. ({objectKey: newNameForObjectKey, ...rest}) => ({...rest, newNameForObjectKey}).
The object rest spread (...rest) gives you an object, that contains every key, you did not specify in the destructuring.

I hope this will help to avoid problems --like the one you described-- in the future 😊

Collapse
 
damcosset profile image
Damien Cosset • Edited

Yeah, putting the moment() inside the td element would have been simpler indeed :D When you're stuck on a problem, it seems like certain things are invisible to you :)

I actually never thought about using destructuring with .map(), this could be really useful!