Concept
"Hashmap" is a fun buzz word.
I ran into a problem where the API I was using supplied comments with a user_id instead of a username. This was an API I made and the right way to fix it might have been to adjust what the main API fetch gave back but I was in a time crunch and was able to create a quick solution using a hashmap
What I did was at the App level of the React app I did one extra fetch to all Users and created a hashmap to pass down and replace a user ID with a username.
What is a hashmap?
A hashmap is often like a mini dictionary. We can use it to store the outputs of some computationally heavy functions in an object so that the functions don't need to be run multiple times once we know what the outputs are.
In this case we want to create a "dictionary" that relates user_id to username. So it will look something like this.
hashmap = {
id1: "user 1"
id2: "user 2"
}
Now wherever we have a user_id in our code we can replace that with
hashmap[user_id]
and get the username itself.
Code
Here's how I implemented it in a React app with a Sinatra & Ruby backend.
Add state for storing hash
const [ userHash, setUserHash ] = useState();
Add a new fetch...
useEffect(() => {
fetch("http://localhost:9292/userhash")
.then(resp => resp.json())
.then(data => {setUserHash(data)});
}, []);
In Application Controller
get "/userhash" do
userhash = {}
User.all.map{|u| userhash[u.id] = u.username }
userhash.to_json
end
Now our fetch gives us back...
// 20221011094622
// http://localhost:9292/userhash
{
"50": "DaddyCham",
"51": "Mullet",
"52": "Cass",
"53": "bigsis"
}
🚨 PASS USERHASH TO COMPONENTS IT'LL BE USED 🚨
Now where we had for example...
{comment.user_id}:}
we can replace that with...
{userHash[comment.user_id]}:
And we get our correctly attributed comment:
Hope this helps someone out!
-Elliot/Big Sis
Top comments (1)
Thanks for sharing your expertise 🙌