go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/examples/reactjs/example_app/src/store/counter_slice.ts (about)

     1  // Copyright 2022 The LUCI Authors.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  import { createSlice, PayloadAction } from '@reduxjs/toolkit';
    16  import type { RootState } from '@/store/store';
    17  
    18  // Define a type for the slice state
    19  interface CounterState {
    20    value: number
    21  }
    22  
    23  // Define the initial state using that type
    24  const initialState: CounterState = {
    25    value: 0,
    26  };
    27  
    28  export const counterSlice = createSlice({
    29    name: 'counter',
    30    // `createSlice` will infer the state type from the `initialState` argument
    31    initialState,
    32    reducers: {
    33      increment: (state) => {
    34        state.value += 1;
    35      },
    36      decrement: (state) => {
    37        state.value -= 1;
    38      },
    39      // Use the PayloadAction type to declare the contents of `action.payload`
    40      incrementByAmount: (state, action: PayloadAction<number>) => {
    41        state.value += action.payload;
    42      },
    43    },
    44  });
    45  
    46  export const { increment, decrement, incrementByAmount } = counterSlice.actions;
    47  
    48  // Other code such as selectors can use the imported `RootState` type
    49  export const selectCount = (state: RootState) => state.counter.value;
    50  
    51  export default counterSlice.reducer;