Skip to content

Add Redux #18

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

Merged
merged 1 commit into from
Apr 22, 2023
Merged
Show file tree
Hide file tree
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
3 changes: 3 additions & 0 deletions jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,9 @@ export default {
// A map from regular expressions to paths to transformers
// transform: {},
extensionsToTreatAsEsm: [".ts", ".tsx"],
setupFiles: [
"./setupJestMock.ts",
],

// An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation
// transformIgnorePatterns: [
Expand Down
10 changes: 7 additions & 3 deletions library.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,15 @@ import * as React from "react";
import * as ReactDOM from "react-dom/client";
import { BrowserRouter } from "react-router-dom";
import App from "./src/App";
import { Provider } from 'react-redux';
import { store } from './src/store';

const domNode = document.getElementById("root");
const root = ReactDOM.createRoot(domNode);
root.render(
<BrowserRouter>
<App />
</BrowserRouter>,
<Provider store={store}>
<BrowserRouter>
<App />
</BrowserRouter>
</Provider>,
);
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@
"dependencies": {
"@headlessui/react": "^1.7.13",
"@heroicons/react": "^2.0.16",
"@reduxjs/toolkit": "^1.9.5",
"@tailwindcss/forms": "^0.5.3",
"@types/node": "^18.15.9",
"cookie-parser": "^1.4.6",
Expand All @@ -66,6 +67,7 @@
"react-dom": "^18.2.0",
"react-draggable": "^4.4.5",
"react-quill": "^2.0.0",
"react-redux": "^8.0.5",
"react-router-dom": "^6.9.0",
"syllable": "^5.0.1"
},
Expand Down
17 changes: 17 additions & 0 deletions setupJestMock.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
const localStorageMock = {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since the initial state calls local storage, and the utils file needs a dispatcher, this sadly forces Jest to call local storage which does not exist. This mock is put in place to fix it.

store: {},
getItem(key) {
return this.store[key];
},
setItem(key, value) {
this.store[key] = value.toString();
},
clear() {
this.store = {};
},
removeItem(key) {
delete this.store[key];
},
};

Object.defineProperty(global, 'localStorage', { value: localStorageMock });
9 changes: 5 additions & 4 deletions src/BookList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ import ListItem from "./ListItem";
import Popup from "./Popup";
import { getCsrfToken } from "./utils";
import * as fd from "./fetchData";
import { useDispatch } from "react-redux";
import { librarySlice } from "./reducers/librarySlice";

async function deleteBook(bookid: string, onDelete) {
const res = await fd.deleteBook(bookid);
Expand Down Expand Up @@ -36,7 +38,7 @@ async function newBook(dispatch) {
} else {
const book = res.payload;
console.log("new book", book);
dispatch({ type: "ADD_BOOK", payload: book });
dispatch(librarySlice.actions.addBook(book));
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If you look at the quick start we can make this even easier:
https://redux-toolkit.js.org/tutorials/quick-start

by doing something like: export const { increment, decrement, incrementByAmount } = librarySlice.actions

The problem is we have A LOT of actions. I think this is something we can reevaluate and clean up later

}
}

Expand All @@ -49,17 +51,16 @@ export default function BookList({
onChange,
onDelete,
saveBook,
dispatch,
canCloseSidebar = true,
}: {
books: t.Book[];
selectedBookId: string;
onChange: () => void;
onDelete: (bookid: string) => void;
saveBook: (book: t.Book) => void;
dispatch: React.Dispatch<any>;
canCloseSidebar?: boolean;
}) {
const dispatch = useDispatch();
const [showPopup, setShowPopup] = React.useState(false);
const [currentBook, setCurrentBook] = React.useState(books[0]);

Expand Down Expand Up @@ -92,7 +93,7 @@ export default function BookList({
const rightMenuItem = canCloseSidebar && {
label: "Close",
icon: <XMarkIcon className="w-4 h-4 xl:w-5 xl:h-5" />,
onClick: () => dispatch({ type: "CLOSE_BOOK_LIST" }),
onClick: () => dispatch(librarySlice.actions.closeBookList()),
className: buttonStyles,
};

Expand Down
11 changes: 8 additions & 3 deletions src/ChapterList.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ import { BrowserRouter } from "react-router-dom";
import { render, fireEvent, screen } from "@testing-library/react";
import "@testing-library/jest-dom";
import { act } from "react-dom/test-utils";
import { store } from "./store";
import { Provider } from 'react-redux';

const props = {
chapters: [chapter1, chapter2],
Expand All @@ -36,9 +38,12 @@ describe("ChapterList", () => {
let container;
beforeEach(() => {
const res = render(
<BrowserRouter>
<ChapterList {...props} />
</BrowserRouter>,

<Provider store={store}>
<BrowserRouter>
<ChapterList {...props} />
</BrowserRouter>
</Provider>,
);
container = res.container;
});
Expand Down
21 changes: 11 additions & 10 deletions src/ChapterList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ import ListMenu from "./ListMenu";
import ListItem from "./ListItem";
import Popup from "./Popup";
import { getCsrfToken } from "./utils";
import { useDispatch } from "react-redux";
import { librarySlice } from "./reducers/librarySlice";
// import Draggable from "react-draggable";

export default function ChapterList({
Expand All @@ -27,7 +29,6 @@ export default function ChapterList({
onDelete,
saveChapter,
closeSidebar,
dispatch,
canCloseSidebar = true,
}: {
chapters: t.Chapter[];
Expand All @@ -37,24 +38,24 @@ export default function ChapterList({
onDelete: any;
saveChapter: any;
closeSidebar: () => void;
dispatch: React.Dispatch<t.ReducerAction>;
canCloseSidebar?: boolean;
}) {
const dispatch = useDispatch();
const [editing, setEditing] = React.useState(false);
const [showPopup, setShowPopup] = React.useState(false);
const [currentChapter, setCurrentChapter] = React.useState(chapters[0]);

async function deleteChapter(chapterid: string) {
console.log("delete chapter", chapterid);
dispatch({ type: "LOADING" });
dispatch(librarySlice.actions.loading);
const res = await fetch(`/api/deleteChapter`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ bookid, chapterid, csrfToken: getCsrfToken() }),
});
dispatch({ type: "LOADED" });
dispatch(librarySlice.actions.loaded);
if (!res.ok) {
console.log(res.statusText);
return;
Expand All @@ -64,15 +65,15 @@ export default function ChapterList({

async function favoriteChapter(chapterid: string) {
console.log("favorite chapter", chapterid);
dispatch({ type: "LOADING" });
dispatch(librarySlice.actions.loading());
const res = await fetch(`/api/favoriteChapter`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ bookid, chapterid, csrfToken: getCsrfToken() }),
});
dispatch({ type: "LOADED" });
dispatch(librarySlice.actions.loaded());
if (!res.ok) {
console.log(res.statusText);
return;
Expand All @@ -81,11 +82,11 @@ export default function ChapterList({
}

const newChapter = async (title = "New Chapter", text = "") => {
dispatch({ type: "LOADING" });
dispatch(librarySlice.actions.loading());
const result = await fd.newChapter(bookid, title, text);
dispatch({ type: "LOADED" });
dispatch(librarySlice.actions.loaded());
if (result.tag === "error") {
dispatch({ type: "SET_ERROR", payload: result.message });
dispatch(librarySlice.actions.setError(result.message));
return;
}
await onChange();
Expand Down Expand Up @@ -120,7 +121,7 @@ export default function ChapterList({
const [removed] = ids.splice(result.source.index, 1);
ids.splice(result.destination.index, 0, removed);

dispatch({ type: "SET_CHAPTER_ORDER", payload: { bookid, ids } });
dispatch(librarySlice.actions.setChapterOrder({ bookid, ids }));
};

const sublist = () => chapters.map((chapter, index) => (
Expand Down
17 changes: 8 additions & 9 deletions src/Editor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,17 @@ import "./globals.css";
import TextEditor from "./TextEditor";
import * as t from "./Types";
import { getCsrfToken } from "./utils";
import { useDispatch, useSelector } from "react-redux";
import { RootState } from "./store";
import { librarySlice } from "./reducers/librarySlice";

export default function Editor({
state,
dispatch,
onSave,
}: {
state: t.State;
dispatch: React.Dispatch<t.ReducerAction>;
onSave: (state: t.State) => void;
}) {
const state = useSelector((state: RootState) => state.library);
const dispatch = useDispatch();
async function saveChapter(state: t.State) {
if (state.saved) return;
if (!state.chapter) {
Expand All @@ -33,10 +34,10 @@ export default function Editor({
});

if (!result.ok) {
dispatch({ type: "SET_ERROR", payload: result.statusText });
dispatch(librarySlice.actions.setError(result.statusText));
} else {
dispatch({ type: "CLEAR_ERROR" });
dispatch({ type: "SET_SAVED", payload: true });
dispatch(librarySlice.actions.clearError());
dispatch(librarySlice.actions.setSaved(true));
}
}

Expand All @@ -57,8 +58,6 @@ export default function Editor({
</div>
<div className="h-full w-full">
<TextEditor
dispatch={dispatch as any}
state={state.editor}
chapterid={state.chapter.chapterid}
saved={state.saved}
onSave={() => onSave(state)}
Expand Down
Loading