Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split Redux actions into multiple files

Tags:

redux

I have an actions folder with the usual types.js file for my action type constants, plus an index.js file that does the following

import axios from 'axios';
import { browserHistory } from 'react-router';
import {
  AUTH_USER,
  UNAUTH_USER,
  AUTH_ERROR,
  FETCH_MESSAGE
} from './types';

and also exports functions for all my actions. I'm wondering, is there a way I can create multiple files for defining my actions so index.js doesn't become too long, then import those into my index.js so in my components I can still just do for example import { loginUser } from '../../actions'; and not have to worry about which file the action is coming from?

like image 729
Chris Avatar asked Feb 01 '17 00:02

Chris


2 Answers

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'
like image 154
nbkhope Avatar answered Nov 20 '22 14:11

nbkhope


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'
like image 38
cdaiga Avatar answered Nov 20 '22 15:11

cdaiga