How to split Redux actions into multiple files

Say for example we have two actions files; actionsA and ActionsB. Suppose in actionsA we have the following action functions.

//actionsA

//You can import your actionTypes here
export function functionActionsA1(){ /* action body ActionsA1 */}

export function functionActionsA2(){ /* action body ActionsA2 */}

and in actionsB we have the following code:

//actionsB

//You can import your actionTypes here

export function functionActionsB1(){ /* action body ActionsB1 */}

export function functionActionsB2(){ /* action body ActionsB2 */}

Say we have a folder actions containing the two files; actionsA and actionsB, and an index.js file.

actions/ 
   index.js
   actionsA.js
   actionsB.js

In index.js file we import the different actions from actionsA and actionsB and then exports the imported functions.

//index.js
import {functionActionsA1, functionActionsA2 } from './actionsA'
import {functionActionsB1, functionActionsB2} from './actionsB'

export functionActionsA1
export functionActionsA2
export functionActionsB1
export functionActionsB2

Now you can just import your index file and get the actions you would want to use as shown below:

import {functionActionsA1,functionActionsB2} from '../../actions/index'

Assuming you have the following directory structure:

actions/
  index.js
  types.js
  ProductActions.js

Inside your actions/index.js, write:

export * from './ProductActions';

Then define ProductActions.js as something like:

import axios from 'axios';
import { ... } from './types';

export const fetchProducts = () => { ... };
export const deleteProduct = () => { ... };

Remember to also update your reducers with the new action types file:

import { ... } from '../actions/types'

Tags:

Redux