buttons-reducer.js
43 lines
| 1 | import { createSlice } from '@reduxjs/toolkit'; |
| 2 | |
| 3 | const initialState = { |
| 4 | buttons: {}, |
| 5 | }; |
| 6 | |
| 7 | const buttonsSlice = createSlice( { |
| 8 | name: 'buttons', |
| 9 | initialState, |
| 10 | reducers: { |
| 11 | closeDropdown: ( state, action ) => { |
| 12 | const { id } = action.payload; |
| 13 | state.buttons[ id ] = { ...state.buttons[ id ], isDropdownOpen: false }; |
| 14 | }, |
| 15 | openDropdown: ( state, action ) => { |
| 16 | const { id } = action.payload; |
| 17 | state.buttons[ id ] = { ...state.buttons[ id ], isDropdownOpen: true }; |
| 18 | }, |
| 19 | toggleDropdown: ( state, action ) => { |
| 20 | const { id } = action.payload; |
| 21 | state.buttons[ id ] = { ...state.buttons[ id ], isDropdownOpen: ! state.buttons[ id ]?.isDropdownOpen }; |
| 22 | }, |
| 23 | closeAllDropdowns: ( state, action ) => { |
| 24 | const idToExclude = action?.payload?.id; |
| 25 | Object.keys( state.buttons ).forEach( id => { |
| 26 | if ( idToExclude !== id ) { |
| 27 | state.buttons[ id ].isDropdownOpen = false |
| 28 | } |
| 29 | } ); |
| 30 | }, |
| 31 | }, |
| 32 | } ); |
| 33 | |
| 34 | const { actions, reducer } = buttonsSlice; |
| 35 | |
| 36 | export const { |
| 37 | openDropdown, |
| 38 | closeDropdown, |
| 39 | toggleDropdown, |
| 40 | closeAllDropdowns, |
| 41 | } = actions; |
| 42 | |
| 43 | export default reducer; |