Recently, I’ve been working on a React application that is proving to be just the fruitful learning experience I’d hoped for. My partner and I are building a Tarot Card Reading app (fun! 🔮). Although there is a plethora of different card spreads one can perform in the world of tarot card reading, we decided to start with just a simple 3-card past/present/future spread like so:
In order to achieve this, we needed to write a function that could select 3 different cards from our database(AKA deck of tarot cards) at random(AKA through clairvoyance) without choosing the same card twice. So how did we do it?
First of all, we created a database with Ruby on Rails to hold all of our card data. I will not go into that here, but just know that the “/card” route contains all the cards.
In our React Component, we first call a fetch method to get all of the cards from the database and store them in the state using the { useState } hook.
Great, so this means that we can refer to the card variable anywhere else in this component to get the array of all our cards. That is what we do in the getThreeCards function below. We also created a threecards variable using the { useState } hook again, so that we can fill it with our three randomly selected cards later.
To break down what we are doing here, we are:
Finally, we can’t forget to call the getThreeCards function within the return statement of our component, to render our cards in JSX to the DOM.
And finally, on click of a button, you will get your 3-card tarot spread on the screen! Much cheaper than a psychic. 😁