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

P2022-1143 [Spike] Redux v.s. Redux Toolkit #67

Draft
wants to merge 16 commits into
base: main
Choose a base branch
from
Draft
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
77 changes: 52 additions & 25 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,44 +1,71 @@
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app), using the [Redux](https://redux.js.org/) and [Redux Toolkit](https://redux-toolkit.js.org/) template.
# Redux

## Available Scripts
> "A Predictable State Container for JS Apps"

In the project directory, you can run:
## General info

### `npm start`
https://redux.js.org/introduction/getting-started

Runs the app in the development mode.<br />
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
- used to manage the global state of the application
- requires adherence to certain specific rules
- gives specific patterns and tools Thanks to that it's easy to understand
when, where, how, why is the status of our application updated

The page will reload if you make edits.<br />
You will also see any lint errors in the console.
### Disadvantages

### `npm test`
- requires us to use specific patterns
- requires familiarization with the tool
- increases the amount of code

Launches the test runner in the interactive watch mode.<br />
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
### When to use?

### `npm run build`
- the state of the application is extensive and access to it is needed in many places
- changes frequently
- the state updating logic is complicated
- the application is quite large

Builds the app for production to the `build` folder.<br />
It correctly bundles React in production mode and optimizes the build for the best performance.
### When NOT to use?

The build is minified and the filenames include the hashes.<br />
Your app is ready to be deployed!
- in forms
- when data is only needed in one component
- when we don't need to 'jump' between actions

See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
## Redux toolkit

### `npm run eject`
> "The official, opinionated, batteries-included toolset for efficient Redux development"

**Note: this is a one-way operation. Once you `eject`, you can’t go back!**
### Example usage

If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
- [example store](https://github.com/intive/patronage22-bialystok-js-simple-jira/blob/P2022-1143/src/state/storeWithToolkit.ts)
- [example slice](https://github.com/intive/patronage22-bialystok-js-simple-jira/blob/P2022-1143/src/views/SecondPage/countSlice.ts)
- [example slice with redux-thunk](https://github.com/intive/patronage22-bialystok-js-simple-jira/blob/P2022-1143/src/views/Projects/projectsSlice.ts)

Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own.
### What's included?

You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it.
https://redux.js.org/redux-toolkit/overview#whats-included

## Learn More
- configureStore
- createReducer
- createAction
- createSlice
- createAsyncThunk
- createEntityAdapter
- createSelector

You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
### Why use toolkit?

To learn React, check out the [React documentation](https://reactjs.org/).
https://redux.js.org/redux-toolkit/overview#why-you-should-use-redux-toolkit

- do more work with less code
- redux-thunk included
- redux dev tools extension configured

- 'createSlice' simplifies creating actions, action-creators and reducer
- 'createSlice' automatically creates actions and returns them in property 'actions'
- 'slice' is a part of app state, f.ex. every feature has its own slice
- thanks to 'immer' library we can write reducers code without worrying about Immutability
- 'nanoid' out of the box

and much more...

Checkout full description on [redux-toolkit website](https://redux-toolkit.js.org/) and learn how to [use it with typescript](https://redux-toolkit.js.org/tutorials/typescript)
9 changes: 9 additions & 0 deletions public/exampleProjects.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
[
{ "id": 1, "name": "Project1" },
{ "id": 2, "name": "Death Star" },
{ "id": 3, "name": "Conquer The World" },
{ "id": 4, "name": "Branch Party Project" },
{ "id": 5, "name": "Find out who killed Kennedy" },
{ "id": 6, "name": "Catch Them All" },
{ "id": 7, "name": "Watermelon Jam" }
]
7 changes: 5 additions & 2 deletions src/components/Counter/Counter.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,18 @@ import { useSelector } from "react-redux";
import { RootState } from "../../state/reducers";
import { useTranslation } from "react-i18next";
import { CounterWrapper, CounterNumber } from "./Counter.style";
import { selectCountValue } from "../../views/SecondPage/countSlice";
import { useAppSelector } from "../../state/storeHooks";

export const Counter = () => {
const state = useSelector((state: RootState) => state.bank);
// const state = useSelector((state: RootState) => state.bank);
const count = useAppSelector(selectCountValue);
const { t } = useTranslation();

return (
<CounterWrapper>
<p>{t("paragraph4")}</p>
<CounterNumber>{state}</CounterNumber>
<CounterNumber>{count}</CounterNumber>
</CounterWrapper>
);
};
5 changes: 3 additions & 2 deletions src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,14 @@ import ReactDOM from "react-dom";
import "./index.css";
import App from "./App";
import { Provider } from "react-redux";
import { store } from "./state/index";
// import { store } from "./state/index";
import storeWithToolkit from "./state/storeWithToolkit";
import { BrowserRouter } from "react-router-dom";
import "./translations/i18n";

ReactDOM.render(
<React.StrictMode>
<Provider store={store}>
<Provider store={storeWithToolkit}>
<BrowserRouter>
<App />
</BrowserRouter>
Expand Down
5 changes: 5 additions & 0 deletions src/state/storeHooks.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { TypedUseSelectorHook, useDispatch, useSelector } from "react-redux";
import { AppDispatch, RootState } from "./storeWithToolkit";

export const useAppDispatch = () => useDispatch<AppDispatch>();
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector;
15 changes: 15 additions & 0 deletions src/state/storeWithToolkit.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { configureStore } from "@reduxjs/toolkit";
import countReducer from "../views/SecondPage/countSlice";
import projectsReducer from "../views/Projects/projectsSlice";

const store = configureStore({
reducer: {
count: countReducer,
projects: projectsReducer,
},
});

export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;

export default store;
73 changes: 52 additions & 21 deletions src/views/Projects/Projects.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,31 +3,62 @@ import ProjectCard from "../../components/ProjectCard";
import ThreeDotsMenu from "../../components/ThreeDotsMenu/ThreeDotsMenu";
import { StyledProjectList, StyledPageWrapper } from "./Projects.style";
import { mockMenuItems } from "../../mockData/menuItems";
import { mockProjects } from "../../mockData/mockProjects";
// import { mockProjects } from "../../mockData/mockProjects";
import { useTranslation } from "react-i18next";
import Grid from "@mui/material/Grid";
import { useEffect } from "react";
import { useAppDispatch, useAppSelector } from "../../state/storeHooks";
import {
fetchProjects,
selectProjects,
selectProjectsStatus,
Status,
} from "./projectsSlice";

export const Projects = () => {
const status = useAppSelector(selectProjectsStatus);
const projects = useAppSelector(selectProjects);

const dispatch = useAppDispatch();
const { t } = useTranslation();
return (
<StyledPageWrapper>
<PageHeader
pageTitle={t("projectsViewTitle")}
buttonText={t("newProjectBtn")}
buttonHandler={() => console.log("works")}
/>
<StyledProjectList>
<Grid container spacing={3}>
{mockProjects.map((project, id) => (
<Grid key={id} item xs={12} sm={12} md={6} lg={4} xl={3}>
<ProjectCard
menuComponent={<ThreeDotsMenu menuItems={mockMenuItems} />}
name={project.name}
/>

useEffect(() => {
const promise = dispatch(fetchProjects());

return () => promise.abort();
}, []);

switch (status) {
case Status.LOADING:
return <div style={{ marginTop: 300 }}>Loading...</div>;

case Status.SUCCESS:
return (
<StyledPageWrapper>
<PageHeader
pageTitle={t("projectsViewTitle")}
buttonText={t("newProjectBtn")}
buttonHandler={() => console.log("works")}
/>
<StyledProjectList>
<Grid container spacing={3}>
{projects.map((project, id) => (
<Grid key={id} item xs={12} sm={12} md={6} lg={4} xl={3}>
<ProjectCard
menuComponent={<ThreeDotsMenu menuItems={mockMenuItems} />}
name={project.name}
/>
</Grid>
))}
</Grid>
))}
</Grid>
</StyledProjectList>
</StyledPageWrapper>
);
</StyledProjectList>
</StyledPageWrapper>
);

case Status.ERROR:
return <div style={{ marginTop: 300 }}>Error!!!</div>;

default:
return null;
}
};
3 changes: 3 additions & 0 deletions src/views/Projects/delay.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export const delay = (ms: number) => {
return new Promise((resolve) => setTimeout(resolve, ms));
};
73 changes: 73 additions & 0 deletions src/views/Projects/projectsSlice.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";

import { RootState } from "../../state/storeWithToolkit";
import { delay } from "./delay";

const DEMO_DELAY = 3000;

export const fetchProjects = createAsyncThunk(
"projects/getProjects",
async (_, thunkAPI) => {
try {
await delay(DEMO_DELAY);

const response = await fetch("./exampleProjects.json", {
signal: thunkAPI.signal,
});

return await response.json();
} catch {
console.error("An error has occurred!");
return await Promise.reject();
}
}
);

export enum Status {
INITIAL = "initial",
LOADING = "loading",
SUCCESS = "success",
ERROR = "error",
}

export interface Project {
id: number;
name: string;
}

interface SliceState {
status: Status;
projects: Project[];
}

const initialState = {
status: Status.INITIAL,
} as SliceState;

const projectsSlice = createSlice({
name: "projects",
initialState,
reducers: {},
extraReducers: (builder) => {
builder.addCase(fetchProjects.pending, (state) => {
state.status = Status.LOADING;
});
builder.addCase(fetchProjects.rejected, (state) => {
state.status = Status.ERROR;
});
builder.addCase(fetchProjects.fulfilled, (state, action) => {
state.projects = action.payload;
state.status = Status.SUCCESS;
});
},
});

const selectProjectsState = (state: RootState) => state.projects;

export const selectProjectsStatus = (state: RootState) =>
selectProjectsState(state).status;

export const selectProjects = (state: RootState) =>
selectProjectsState(state).projects;

export default projectsSlice.reducer;
15 changes: 9 additions & 6 deletions src/views/SecondPage/SecondPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,23 +8,26 @@ import { Counter } from "../../components/Counter/Counter";
import TasksCard from "../../components/TasksCard";

//Store
import { useDispatch } from "react-redux";
import { bindActionCreators } from "redux";
import { actionCreators } from "../../state";
// import { useDispatch } from "react-redux";
// import { bindActionCreators } from "redux";
// import { actionCreators } from "../../state";
import Ticket from "../../components/Ticket/Ticket";
import ProjectCard from "../../components/ProjectCard";
import ThreeDotsMenu from "../../components/ThreeDotsMenu/ThreeDotsMenu";
import { mockMenuItems } from "../../mockData/menuItems";
import { add } from "./countSlice";
import { useAppDispatch } from "../../state/storeHooks";

export const SecondPage = () => {
const dispatch = useDispatch();
const dispatch = useAppDispatch();
const { t } = useTranslation();

const clickHandler = () => {
console.log("Button works");
adding();
// adding();
dispatch(add());
};
const { adding } = bindActionCreators(actionCreators, dispatch);
// const { adding } = bindActionCreators(actionCreators, dispatch);

const generateKey = (pre: any) => {
return `${pre}_${new Date().getTime()}`;
Expand Down
25 changes: 25 additions & 0 deletions src/views/SecondPage/countSlice.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { createSlice } from "@reduxjs/toolkit";

import { RootState } from "../../state/storeWithToolkit";

const initialState = {
count: 0,
};

const countSlice = createSlice({
name: "count",
initialState,
reducers: {
add: (state) => ({
count: state.count + 1,
}),
},
});

export const { add } = countSlice.actions;

const selectCountState = (state: RootState) => state.count;
export const selectCountValue = (state: RootState) =>
selectCountState(state).count;

export default countSlice.reducer;