Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

update side-by-side example to match the current official recommendations on how to write redux code #2

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
85 changes: 20 additions & 65 deletions src/pages/comparison.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,75 +8,30 @@ Let's compare a subset of the chat app from the official Redux docs, then rewrit
## Redux

```ts
// src/store/chat/types.ts
export interface Message {
user: string
message: string
timestamp: number
}

export interface ChatState {
messages: Message[]
}

export const SEND_MESSAGE = 'SEND_MESSAGE'
export const DELETE_MESSAGE = 'DELETE_MESSAGE'

interface SendMessageAction {
type: typeof SEND_MESSAGE
payload: Message
}

interface DeleteMessageAction {
type: typeof DELETE_MESSAGE
meta: {
timestamp: number
}
}

export type ChatActionTypes = SendMessageAction | DeleteMessageAction
import { createSlice, PayloadAction } from "@reduxjs/toolkit";

// src/store/chat/actions.ts
export function sendMessage(newMessage: Message): ChatActionTypes {
return {
type: SEND_MESSAGE,
payload: newMessage
}
}

export function deleteMessage(timestamp: number): ChatActionTypes {
return {
type: DELETE_MESSAGE,
meta: {
timestamp
}
}
interface Message {
user: string;
message: string;
timestamp: number;
}

// src/store/chat/reducers.ts
const initialState: ChatState = {
messages: []
}
const slice = createSlice({
name: "messages",
initialState: [] as Message[],
reducers: {
send(state, action: PayloadAction<Message>) {
state.push(action.payload);
},
deleteByTimestamp(state, action: PayloadAction<number>) {
const index = state.findIndex((msg) => msg.timestamp === action.payload);
if (index >= 0) delete state[index];
},
},
});

export function chatReducer(
state = initialState,
action: ChatActionTypes
): ChatState {
switch (action.type) {
case SEND_MESSAGE:
return {
messages: [...state.messages, action.payload]
}
case DELETE_MESSAGE:
return {
messages: state.messages.filter(
message => message.timestamp !== action.meta.timestamp
)
}
default:
return state
}
}
export default slice.reducer;
export const { send, deleteByTimestamp } = slice.actions;
```

## Wire
Expand Down