One time array loop
Today, we will discuss about a mistake that many developers have made:
Map, then Map and Map again…
The story started with calling an api:
const arrMessages = await api.get(“/messages/get-last-room-messages”, {room_id: 123})
The array arrMessages is a list of about 50 data items.
Now, the first Map: rename keys in the data items
const arrMessageViews = arrMessages.map(item => {return {roomId: item.room_id, userId: item.user_id, content: item.content}})
Next, the second Map: add user info
const arrWithUserMessageViews = arrMessageViews.map(item => {return {roomId: item.roomId, userId: item.userId, content: item.content, username: Users[item.userId]}})
The last Map: view messages in JSX
let i = 0
{arrWithUserMessageViews.map(item => { return (<p key={i++}><div>{item.username}: {item.content}</div></p>)})}
The arrMessages map, map and map multiple times just to modify data and view. Ohhh noooo….
So, how to get better now?
Good news is I have a solution for this habit: npm install loopable
With this package we just loop the array one time for all!
How to do this?
import {make} from “loopable”
const arrMessages = api.get(“/messages/get-last-room-messages”, {room_id: 123})
const loopable = make(arrMessages) //Make it loopable
With the first map, we just add a modifier:
loopable.add(item => {return {roomId: item.room_id, userId: item.user_id, content: item.content}})
The second one, just add second modifier:
loopable.add(item => {return {roomId: item.roomId, userId: item.userId, content: item.content, username: Users[item.userId]}})
The last one, just loop:
{
loopable.loop((item, index) => { return (<p key={index}><div>{item.username}: {item.content}</div></p>)})
}
So, with this package the array only loop one time and modified multiple times.
Delicious! :)
P/S: After call loopable.loop, the first array arrMessages also modified. So we can use it again.
Git: https://gitlab.com/mrbaobao/test-loopable
#loopable #onetimeloop #reactjs