構成
src/
├── store/
│ ├── alert/
│ │ ├── actions.ts
│ │ ├── reducer.ts
│ │ └── types.ts
│ └── index.ts
types.ts
// src/store/alert/types.ts
export const SHOW_ALERT = 'SHOW_ALERT';
export const HIDE_ALERT = 'HIDE_ALERT';
export type AlertState = 'show' | 'hidden';
interface ShowAlertAction {
type: typeof SHOW_ALERT;
}
interface HideAlertAction {
type: typeof HIDE_ALERT;
}
export type AlertActionTypes = ShowAlertAction | HideAlertAction;
actions.ts
// src/store/alert/actions.ts
import { SHOW_ALERT, HIDE_ALERT, AlertActionTypes } from './types';
export const showAlert = (): AlertActionTypes => ({
type: SHOW_ALERT,
});
export const hideAlert = (): AlertActionTypes => ({
type: HIDE_ALERT,
});
reducer.ts
// src/store/alert/reducer.ts
import { AlertState, AlertActionTypes, SHOW_ALERT, HIDE_ALERT } from './types';
const initialState: AlertState = 'hidden';
export const alertReducer = (
state = initialState,
action: AlertActionTypes
): AlertState => {
switch (action.type) {
case SHOW_ALERT:
return 'show';
case HIDE_ALERT:
return 'hidden';
default:
return state;
}
};
index.ts
// src/store/index.ts
import { createStore, combineReducers } from 'redux';
import { alertReducer } from './alert/reducer';
const rootReducer = combineReducers({
alert: alertReducer,
});
export type RootState = ReturnType<typeof rootReducer>;
export const store = createStore(rootReducer);
src/
├── store/
│ ├── alertSlice.ts
│ └── index.ts
alertSlice.ts
// src/store/alertSlice.ts
import { createSlice } from '@reduxjs/toolkit';
export type AlertState = 'show' | 'hidden';
const initialState: AlertState = 'hidden';
const alertSlice = createSlice({
name: 'alert',
initialState,
reducers: {
showAlert: (state) => 'show',
hideAlert: (state) => 'hidden',
},
});
export const { showAlert, hideAlert } = alertSlice.actions;
export default alertSlice.reducer;
index.ts
// src/store/index.ts
import { configureStore } from '@reduxjs/toolkit';
import alertReducer from './alertSlice';
export const store = configureStore({
reducer: {
alert: alertReducer,
},
});
export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;