Let's say I am making simple card game in react
using redux
with redux-thunk
middleware
I fetch the deck of cards from external API so my action creator looks like this:
const fetchDeck = {
return dispatch => {
return fetch(https://some.api.with.cards/)
.then(r => r.json())
.then(data => dispatch({type:"FETCH_DECK", deck: data}))
}
}
And the corresponding reducer is:
const deck = (state=[], action) => {
switch(action.type) {
case "FETCH_DECK":
return action.deck
default:
return state
}
}
The response from the API is an array of card objects like this one:
{
name: "ACE",
suit: "CLUBS"
}
So now I want to add hand
prop to the store. hand
is an array containing the cards which are already in the player's hand, so I created an action to allow to draw cards from deck
to hand
:
const drawCard = (deck, numberOfCards) => {
return {
type: "DRAW_CARD",
deck
}
}
And this is the corresponding reducer:
const hand = (state=[], action) {
switch(action.type) {
case "DRAW_CARD":
return [...state.slice(0,action.deck)
default:
return state
}
}
Finally I tried to implement this behaviour in the <Hand>
component:
class Hand extends React.component {
componentDidMount() {
const { deck, drawCards } = this.props;
drawCards(deck, 5)
}
}
But it did not work! The API request is not completed when componentDidMount()
occurs. The only thing came into my mind to handle the problem was:
componentDidUpdate(prevProps) {
if (prevProps.deck.length > 0) {
const { deck, drawCard } = this.props;
drawCard(deck, 5)
}
}
Well this works, but I have the awkward feeling that this is not the proper way to do it. Moreover it would be necessary to use some more condtitions to prevent unexpected behaviour if applied this way.
Is there a better way to handle my problem?