Skip to content

Commit

Permalink
Merge pull request #36 from msutkowski/add-typed-hooks
Browse files Browse the repository at this point in the history
  • Loading branch information
markerikson committed Mar 30, 2021
2 parents 330b872 + 3cd9b18 commit 9539a25
Show file tree
Hide file tree
Showing 4 changed files with 11 additions and 4 deletions.
6 changes: 6 additions & 0 deletions template/src/app/hooks.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { TypedUseSelectorHook, useDispatch, useSelector } from 'react-redux'
import type { RootState, AppDispatch } from './store'

// Use throughout your app instead of plain `useDispatch` and `useSelector`
export const useAppDispatch = () => useDispatch<AppDispatch>()
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector
1 change: 1 addition & 0 deletions template/src/app/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ export const store = configureStore({
},
});

export type AppDispatch = typeof store.dispatch;
export type RootState = ReturnType<typeof store.getState>;
export type AppThunk<ReturnType = void> = ThunkAction<
ReturnType,
Expand Down
6 changes: 3 additions & 3 deletions template/src/features/counter/Counter.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import React, { useState } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import {
decrement,
increment,
Expand All @@ -8,10 +7,11 @@ import {
selectCount,
} from './counterSlice';
import styles from './Counter.module.css';
import { useAppDispatch, useAppSelector } from '../../app/hooks';

export function Counter() {
const count = useSelector(selectCount);
const dispatch = useDispatch();
const count = useAppSelector(selectCount);
const dispatch = useAppDispatch();
const [incrementAmount, setIncrementAmount] = useState('2');

return (
Expand Down
2 changes: 1 addition & 1 deletion template/src/features/counter/counterSlice.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ export const incrementAsync = (amount: number): AppThunk => dispatch => {

// The function below is called a selector and allows us to select a value from
// the state. Selectors can also be defined inline where they're used instead of
// in the slice file. For example: `useSelector((state: RootState) => state.counter.value)`
// in the slice file. For example: `useAppSelector(state => state.counter.value)`
export const selectCount = (state: RootState) => state.counter.value;

export default counterSlice.reducer;

0 comments on commit 9539a25

Please sign in to comment.