Home > OS >  Reactjs: redux toolkit with function same name
Reactjs: redux toolkit with function same name

Time:08-25

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?

CodePudding user response:

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

CodePudding user response:

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

  • Related