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?
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'
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With