0

This is my code:

a.tsx

const initialState = {
    open: false
}

export const a = createSlice({
    name: 'a',
    initialState,
    reducers: {
        show: (state) => {
            state.open = true
        }
    }
});

export const {show} = a.actions;

export default a.reducer;

b.tsx

const initialState = {
    open: false
}

export const b = createSlice({
    name: 'b',
    initialState,
    reducers: {
        show: (state) => {
            state.open = true
        }
    }
});

export const {show} = b.actions;

export default b.reducer;

app.tsx

import { show } from './app/reducer/a'
import { show } from './app/reducer/b';

And I get this error:

Duplicate identifier 'show'

I don't want to change method name to showA and showB.

How can I handle same name of functions?

ali
  • 55
  • 1
  • 6

2 Answers2

0

You cannot import to things with same name in JavaScript, but you can rename it when importing:

import { show } from './app/reducer/a'
import { show as showB } from './app/reducer/b';

show();  // reducer/a
showB();  // reducer/b
Nils Hartmann
  • 466
  • 3
  • 6
  • Is there any way to load all of reducer into one variable? like this: `import a from './app/reducer/a'; a.show();` – ali Aug 24 '22 at 13:23
  • Yes. You could `import * as a from './app/reducer/a'`. You can find more on the import statement of ES6 modules here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import BTW: you're not importing the reducers here, but the action creator functions. – Nils Hartmann Aug 24 '22 at 13:26
0

There isn't any other solution except to use AS.

Either you rename your functions in the original files, or you can use as:

import { show as showA } from './app/reducer/a';
import { show as showB } from './app/reducer/b';

If you want to learn more about imports, you can visit https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import

Jonatan Kruszewski
  • 1,027
  • 3
  • 23