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

redux-setup #12

Closed
wants to merge 1 commit into from
Closed
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
1 change: 1 addition & 0 deletions client/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
"react-scripts": "5.0.1",
"react-utils": "^1.0.0",
"redux": "^4.2.0",
"redux-persist": "^6.0.0",
"redux-thunk": "^2.4.1",
"web-vitals": "^2.1.4"
},
Expand Down
6 changes: 2 additions & 4 deletions client/src/componets/AddBlogs.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Box, Button, InputLabel, TextField, Typography } from "@mui/material";
import axios from "axios";
import TextareaAutosize from '@mui/base/TextareaAutosize';
import TextareaAutosize from "@mui/material/TextareaAutosize";

import React, { useState } from "react";
import { useNavigate } from "react-router-dom";
Expand Down Expand Up @@ -55,7 +55,6 @@ const AddBlogs = () => {
>
<Typography
className={classes.font}

padding={3}
color="grey"
variant="h2"
Expand Down Expand Up @@ -100,7 +99,6 @@ const AddBlogs = () => {
<Button
sx={{ mt: 2, borderRadius: 4 }}
variant="contained"

type="submit"
>
Submit
Expand All @@ -111,4 +109,4 @@ const AddBlogs = () => {
);
};

export default AddBlogs;
export default AddBlogs;
97 changes: 59 additions & 38 deletions client/src/componets/Header.js
Original file line number Diff line number Diff line change
@@ -1,28 +1,36 @@
import React from 'react'
import React from "react";
import { Link } from "react-router-dom";
import { authActions } from "../store";
import { clearCredentials } from "../store/authApiSlice";
import {
AppBar, Typography,Toolbar, Box, Button, Tabs, Tab,
} from "@mui/material";
AppBar,
Typography,
Toolbar,
Box,
Button,
Tabs,
Tab,
} from "@mui/material";
import { useDispatch, useSelector } from "react-redux";

import { useState } from "react";

const Header = () => {
const dispath = useDispatch();
const isLoggedIn = useSelector((state) => state.isLoggedIn);
const [value, setValue] = useState();
const dispath = useDispatch();
const isLoggedIn = useSelector((state) => state.isLoggedIn);
const [value, setValue] = useState();

return <AppBar
position='sticky'
sx={{ background:
"linear-gradient(90deg, rgba(9,113,121,1) 3%, rgba(205,110,231,1) 100%)" }}>

return (
<AppBar
position="sticky"
sx={{
background:
"linear-gradient(90deg, rgba(9,113,121,1) 3%, rgba(205,110,231,1) 100%)",
}}
>
<Toolbar>
<Typography variant='h4'>
BlogsApp
</Typography>
{ isLoggedIn && <Box display="flex" marginLeft={"auto"} marginRight="auto">
<Typography variant="h4">BlogsApp</Typography>
{isLoggedIn && (
<Box display="flex" marginLeft={"auto"} marginRight="auto">
<Tabs
textColor="inherit"
value={value}
Expand All @@ -47,30 +55,42 @@ const Header = () => {
label="Add Blog"
/>
</Tabs>
</Box>}
<Box display="flex" marginLeft="auto">
{!isLoggedIn && (
<> <Button
LinkComponent={Link}
to="login/"
sx={{ margin: 1, fontWeight : 'bold' , color:"white" , borderRadius: 10 }}
</Box>
)}
<Box display="flex" marginLeft="auto">
{!isLoggedIn && (
<>
{" "}
<Button
LinkComponent={Link}
to="login/"
sx={{
margin: 1,
fontWeight: "bold",
color: "white",
borderRadius: 10,
}}
>
Login
Login
</Button>
<Button
LinkComponent={Link}
to="login/"
sx={{ margin: 1, fontWeight : 'bold' , color:"white" , borderRadius: 10 }}
<Button
LinkComponent={Link}
to="login/"
sx={{
margin: 1,
fontWeight: "bold",
color: "white",
borderRadius: 10,
}}
>

SignUp
SignUp
</Button>
</>
)}
</>
)}

{isLoggedIn && (
{isLoggedIn && (
<Button
onClick={() => dispath(authActions.logout())}
onClick={() => dispath(clearCredentials())}
LinkComponent={Link}
to="/login"
variant="contained"
Expand All @@ -80,9 +100,10 @@ const Header = () => {
Logout
</Button>
)}
</Box>
</Box>
</Toolbar>
</AppBar>
}
</AppBar>
);
};

export default Header
export default Header;
11 changes: 6 additions & 5 deletions client/src/componets/Login.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,12 @@ import { Box, Button, TextField, Typography } from "@mui/material";
import React, { useState } from "react";
import axios from "axios";
import { useDispatch } from "react-redux";
import { authActions } from "../store";
import { useLoginStaffMutation } from "../store/authslice";
import { setCredentials } from "../store/authApiSlice";
import { useNavigate } from "react-router-dom";

const Login = () => {
const [login] = useLoginStaffMutation();
const naviagte = useNavigate();
const dispath = useDispatch();
const [inputs, setInputs] = useState({
Expand All @@ -29,7 +31,6 @@ const Login = () => {
})
.catch((err) => console.log(err));


const data = await res.data;
console.log("return");
console.log(data);
Expand All @@ -42,12 +43,12 @@ const Login = () => {
if (isSignup) {
sendRequest("signup")
.then((data) => localStorage.setItem("userId", data.user._id))
.then(() => dispath(authActions.login()))
.then(() => dispath(setCredentials({ token: 1234567 })))
.then(() => naviagte("/blogs"));
} else {
sendRequest()
.then((data) => localStorage.setItem("userId", data.user._id))
.then(() => dispath(authActions.login()))
.then(() => dispath(setCredentials({ token: 1234567 })))
.then(() => naviagte("/blogs"));
}
};
Expand Down Expand Up @@ -114,4 +115,4 @@ const Login = () => {
);
};

export default Login;
export default Login;
30 changes: 16 additions & 14 deletions client/src/index.js
Original file line number Diff line number Diff line change
@@ -1,23 +1,25 @@
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import {BrowserRouter} from 'react-router-dom'
import { Provider } from 'react-redux';
import { store } from './store';
import React from "react";
import ReactDOM from "react-dom/client";
import "./index.css";
import App from "./App";
import { BrowserRouter } from "react-router-dom";
import { Provider } from "react-redux";
import { store } from "./store/index";
import { PersistGate } from "redux-persist/integration/react";
import { persistStore } from "redux-persist";

const root = ReactDOM.createRoot(document.getElementById('root'));
const root = ReactDOM.createRoot(document.getElementById("root"));
let persistor = persistStore(store);
root.render(
<React.StrictMode>
<BrowserRouter>
<Provider store={store}>
<App />

</Provider>
<Provider store={store}>
<PersistGate loading={null} persistor={persistor}>
<App />
</PersistGate>
</Provider>
</BrowserRouter>

</React.StrictMode>

);

// If you want to start measuring performance in your app, pass a function
Expand Down
18 changes: 18 additions & 0 deletions client/src/store/apislice.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { createApi, fetchBaseQuery } from "@reduxjs/toolkit/query/react";

const baseQuery = fetchBaseQuery({
baseUrl: "",
// credentials: "include",
prepareHeaders: (headers, { getState }) => {
const token = getState().auth.token;
if (token) {
headers.set("authorization", `${token}`);
}
return headers;
},
});

export const apiSlice = createApi({
baseQuery,
endpoints: (builder) => ({}),
});
22 changes: 22 additions & 0 deletions client/src/store/authApiSlice.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { createSlice } from "@reduxjs/toolkit";

const authState = createSlice({
name: "authState",
initialState: { user: null, token: null },
reducers: {
setCredentials: (state, action) => {
const { user, token } = action.payload;
state.user = user;
state.token = token;
},
clearCredentials: (state) => {
state.user = null;
state.token = null;
},
},
});

export const { setCredentials, clearCredentials } = authState.actions;
export default authState.reducer;
export const selectUser = (state) => state.auth.user;
export const selectToken = (state) => state.auth.token;
15 changes: 15 additions & 0 deletions client/src/store/authslice.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { apiSlice } from "./apislice";

export const authApiSlice = apiSlice.injectEndpoints({
endpoints: (builder) => ({
loginStaff: builder.mutation({
query: (credentials) => ({
url: "/api/loginStaff",
method: "POST",
body: { ...credentials },
}),
}),
}),
});

export const { useLoginStaffMutation } = authApiSlice;
69 changes: 52 additions & 17 deletions client/src/store/index.js
Original file line number Diff line number Diff line change
@@ -1,21 +1,56 @@
import { configureStore, createSlice } from "@reduxjs/toolkit";
// import { configureStore, createSlice } from "@reduxjs/toolkit";

const authSlice = createSlice({
name: "auth",
initialState: { isLoggedIn: false },
reducers: {
login(state) {
state.isLoggedIn = true;
},
logout(state) {
localStorage.removeItem("userId");
state.isLoggedIn = false;
},
},
});
// const authSlice = createSlice({
// name: "auth",
// initialState: { isLoggedIn: false },
// reducers: {
// login(state) {
// state.isLoggedIn = true;
// },
// logout(state) {
// localStorage.removeItem("userId");
// state.isLoggedIn = false;
// },
// },
// });

// export const authActions = authSlice.actions;

// export const store = configureStore({
// reducer: authSlice.reducer,
// });

export const authActions = authSlice.actions;
import { configureStore } from "@reduxjs/toolkit";
import { apiSlice } from "./apislice";
import {
persistReducer,
FLUSH,
REHYDRATE,
PAUSE,
PERSIST,
PURGE,
REGISTER,
} from "redux-persist";
import storage from "redux-persist/lib/storage";
import authReducer from "./authApiSlice";

const authPersistConfig = {
key: "auth",
storage,
};

const persistedAuthReducer = persistReducer(authPersistConfig, authReducer);

export const store = configureStore({
reducer: authSlice.reducer,
});
reducer: {
[apiSlice.reducerPath]: apiSlice.reducer,
auth: persistedAuthReducer,
},
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware({
serializableCheck: {
ignoredActions: [FLUSH, REHYDRATE, PAUSE, PERSIST, PURGE, REGISTER],
},
}).concat(apiSlice.middleware),
devTools: true,
});