Redux store

We have a standard structure of Redux store:

  • store/

    • reducers/

      • home/

        • types.ts

        • index.ts

    • actions/

      • home.ts

We have this structure of code for actions:

import * as api from 'src/api'
import { Mode } from 'src/api/getPosts'
import { HOME_PREFIX } from '../reducers/home/types'
import { shouldUpdate, getPosts as getCachedPosts } from 'src/utils/cache'

export const getPosts = (mode: Mode, page: number) => async (
  dispatch,
  getState
) => {
  const type = HOME_PREFIX + 'FETCH' // Use FETCH postfix for running a fetch action
  dispatch({ type }) // Dispatch fetch event

  try {
    const data = await api.getPosts(mode, page) // Get data
    const pagesCount = data?.pagesCount

    // Dispatch data with FULFILLED postfix
    dispatch({
      type: type + '_FULFILLED',
      payload: { data: data, mode, page, pagesCount },
    })
  } catch (error) {
    // Dispatch error with REJECTED postfix
    dispatch({ type: type + '_REJECTED', payload: { error, mode, page } })
  }
}

And this structure for reducers:

import { SET_THEME, SET_HIDDEN_AUTHORS, SET_HIDDEN_COMPANIES } from './types'

const initialState = {
  theme,
  themeType,
  hiddenAuthors,
  hiddenCompanies,
}

export default (state = initialState, { type, payload }) => {
  switch (type) {
    case SET_THEME:
      return { ...state, themeType: payload }

    case SET_HIDDEN_AUTHORS:
      return { ...state, hiddenAuthors: payload }

    case SET_HIDDEN_COMPANIES:
      return { ...state, hiddenCompanies: payload }

    default:
      return state
  }
}

To add your own reducer, go to the reducers/index.ts, import your reducer (without index.ts part) and add it to combineReducers function.

Last updated