Reputation: 5379
In the official redux toolkit documentation/tutorial, there's this file (counterSlice.js)
import { createSlice } from '@reduxjs/toolkit'
export const counterSlice = createSlice({
name: 'counter',
initialState: {
value: 0
},
reducers: {
increment: state => {
// Redux Toolkit allows us to write "mutating" logic in reducers. It
// doesn't actually mutate the state because it uses the Immer library,
// which detects changes to a "draft state" and produces a brand new
// immutable state based off those changes
state.value += 1
},
decrement: state => {
state.value -= 1
},
incrementByAmount: (state, action) => {
state.value += action.payload
}
}
})
// Action creators are generated for each case reducer function
export const { increment, decrement, incrementByAmount } = counterSlice.actions
export default counterSlice.reducer
The reducer is then imported in the store:
import { configureStore } from '@reduxjs/toolkit'
import counterReducer from '../features/counter/counterSlice'
export default configureStore({
reducer: {
counter: counterReducer
}
})
As I cannot see any reference to 'counterReducer' in the counterSlice.js file, I assume the 'counterReducer' in the import:
import counterReducer from '../features/counter/counterSlice'
is an arbitratry name and could be any other name of our choice, for example:
import counterSliceReducer from '../features/counter/counterSlice'
Is that correct?
Also, where is this 'reducer' in the default export coming from?
export default counterSlice.reducer
The counterSlice element contains 'reducers' object, not 'reducer'. Is that pulled from under the hood?
Thanks
Upvotes: 1
Views: 727
Reputation: 43
I assume the 'counterReducer' in the import:
import counterReducer from '../features/counter/counterSlice'
is an arbitratry name and could be any other name of our choice
You are correct, it is an ES6 feature, a default export can be imported with any name. see: MDN Page
Also, where is this 'reducer' in the default export coming from?
export default counterSlice.reducer
The counterSlice element contains 'reducers' object, not 'reducer'. Is that pulled from under the hood?
createSlice
API returns an object in a form:
{
name : string,
reducer : ReducerFunction,
actions : Record<string, ActionCreator>,
caseReducers: Record<string, CaseReducer>
}
counterSlice.reducer
is the reducer function, it needs to be exported and then passed to the store.
Upvotes: 1
Reputation: 102267
You can use any name if the imported module uses the export default xxx
method to export the module.
createSlice
will return an object that looks like:
{
name : string,
reducer : ReducerFunction,
actions : Record<string, ActionCreator>,
caseReducers: Record<string, CaseReducer>
}
Take a look at this docs
Upvotes: 1