Skip to content

Instantly share code, notes, and snippets.

@yoovanr
Last active May 1, 2020 17:23
Show Gist options
  • Save yoovanr/15ede8139a91a12755942dbf7ddbbc57 to your computer and use it in GitHub Desktop.
Save yoovanr/15ede8139a91a12755942dbf7ddbbc57 to your computer and use it in GitHub Desktop.
[React] Action and Reducer Examples
import GamesService from '../../services/games'
import store from '../index'
function getGamesAction () {
return async (dispatch) => {
dispatch({ type: 'GET_GAMES_REQUEST'})
try {
const { data } = await GamesService.getGames()
const games = data.data
const lastPage = data.meta.last_page <= data.meta.current_page
dispatch({ type: 'GET_GAMES_SUCCESS', payload: { games, lastPage } })
} catch (err) {
dispatch({ type: 'GET_GAMES_FAILURE' })
}
}
}
function getMoreGamesAction () {
return async (dispatch) => {
dispatch({ type: 'GET_MORE_GAMES_REQUEST' })
let page = store.getState().games.gamesCurrentPage
page++
try {
const { data } = await GamesService.getGames({ page })
const games = data.data
const lastPage = data.meta.last_page <= data.meta.current_page
const currentPage = data.meta.current_page
dispatch({ type: 'GET_MORE_GAMES_SUCCESS', payload: { games, lastPage, currentPage } })
} catch (err) {
dispatch({ type: 'GET_MORE_GAMES_FAILURE' })
}
}
}
function clearGamesAction () {
return (dispatch) => {
dispatch({ type: 'CLEAR_GAMES' })
}
}
export default {
getGamesAction,
getMoreGamesAction,
clearGamesAction
}
const initialState = {
games: [],
gamesLoading: false,
gamesLoadingMore: false,
gamesLastPage: false,
gamesCurrentPage: 1
}
const games = (state = initialState, action) => {
switch (action.type) {
case 'GET_GAMES_REQUEST':
return {
...state,
gamesLoading: true
}
case 'GET_GAMES_SUCCESS':
return {
...state,
games: action.payload.games,
gamesLastPage: action.payload.lastPage,
gamesCurrentPage: 1,
gamesLoading: false
}
case 'GET_GAMES_FAILURE':
return {
...state,
gamesLoading: false
}
case 'GET_MORE_GAMES_REQUEST':
return {
...state,
gamesLoadingMore: true
}
case 'GET_MORE_GAMES_SUCCESS':
return {
...state,
games: [...state.games, ...action.payload.games],
gamesLastPage: action.payload.lastPage,
gamesCurrentPage: action.payload.currentPage,
gamesLoadingMore: false
}
case 'GET_MORE_GAMES_FAILURE':
return {
...state,
gamesLoadingMore: false
}
case 'CLEAR_GAMES':
return {
...state,
games: [],
gamesLoading: false,
gamesLoadingMore: false,
gamesLastPage: false,
gamesCurrentPage: 1
}
default:
return state
}
}
export default games
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment