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

13 feature state management recoil #25

Merged
merged 6 commits into from
Mar 15, 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
8 changes: 7 additions & 1 deletion host/config-overrides.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,14 @@ module.exports = function (config, env) {
config.plugins.push(
new ModuleFederationPlugin(
(module.exports = {
name: "remote",
name: "host",
remotes: {
remote: `remote@http://localhost:3001/remoteEntry.js`,
},
exposes: {
"./atoms": "./src/store/atoms",
},
filename: "remoteEntry.js",
shared: {
...dependencies,
react: {
Expand All @@ -21,6 +25,7 @@ module.exports = function (config, env) {
singleton: true,
requiredVersion: dependencies["react-dom"],
},

},
})
),
Expand All @@ -39,6 +44,7 @@ module.exports = function (config, env) {
"@layouts": path.resolve(__dirname, "src/layouts"),
"@hooks": path.resolve(__dirname, "src/hooks"),
"@utils": path.resolve(__dirname, "src/utils"),
"@api": path.resolve(__dirname, "src/api")
}),
)(config, env)
);
Expand Down
1 change: 1 addition & 0 deletions host/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
"react-dom": "^18.2.0",
"react-router-dom": "^6.7.0",
"react-scripts": "5.0.1",
"recoil": "^0.7.7",
"run-script-os": "^1.1.6",
"swr": "^2.0.4",
"typescript": "^4.9.4",
Expand Down
41 changes: 41 additions & 0 deletions host/src/api/core/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import axios from "axios";

const request = axios.create({
Copy link
Contributor

Choose a reason for hiding this comment

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

요걸 session으로 쓰면 될거같아요

baseURL: "http://localhost:8123"
})

//요청 타임아웃 설정
request.defaults.timeout = 2500;
request.defaults.withCredentials = true;
// request.defaults.headers.common['Authorization'] = `Bearer ${accessToken}`;

//요청 인터셉터 추가
request.interceptors.request.use(
config => { //요청을 보내기 전에 수행할 로직
return config
},
error => {
//요청 에러가 발생했을 때 수행할 로직
console.log(error); //디버깅
return Promise.reject(error);
}
);

//응답 인터셉터 추가
request.interceptors.response.use(
response => {
//응답에 대한 로직 작성
//const res = response.data
//return res
return response
},

error => {
//응답 에러가 발생했을 때 수행할 로직
console.log(error); //디버깅
return Promise.reject(error);
}
);


export default request; //axios 인스턴스를 내보낸다.
Copy link
Contributor

Choose a reason for hiding this comment

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

Restfull 한 return을 return 하면 좋을거 같아요

instance return

return {
      get: (...params) => session.get(...params),
      post: (...params) => session.post(...params),
      put: (...params) => session.put(...params),
      patch: (...params) => session.patch(...params),
      delete: (...params) => session.delete(...params),
    };

저 return 을 하는 instance(request)를 retrun

30 changes: 30 additions & 0 deletions host/src/api/main.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import request from "./core";


export const login = (email: string, password: string) => {
return request(
{
method: 'POST',
url: '/login',
data: {
email: email,
password: password
}
}
)
}

export const loginsuccess = () => {
return request({
// method: 'GET',
url: '/login/success'
});
}

export const logout = () => {
return request({
method: 'POST',
url: '/logout'
});
}

14 changes: 9 additions & 5 deletions host/src/bootstrap.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,21 @@ import App from "./App";
import reportWebVitals from "./reportWebVitals";
import "./index.css";
import { BrowserRouter } from "react-router-dom";
import { RecoilRoot } from 'recoil';


const root = ReactDOM.createRoot(
document.getElementById("root") as HTMLElement
);

root.render(
<BrowserRouter>
<React.StrictMode>
<App />
</React.StrictMode>
</BrowserRouter>
<RecoilRoot>
<BrowserRouter>
<React.StrictMode>
<App />
</React.StrictMode>
</BrowserRouter>
</RecoilRoot>
);

// If you want to start measuring performance in your app, pass a function
Expand Down
23 changes: 12 additions & 11 deletions host/src/pages/LogIn/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,22 +4,23 @@ import fetcher from '@utils/fetcher';
import axios from 'axios';
import React, { useCallback, useState } from 'react';
import useSWR from 'swr';
import { login } from "@api/main"

const LogIn = () => {
const { data: userData, error, mutate } = useSWR('/api/users', fetcher);
// const { data: userData, error, mutate } = useSWR('/api/users', fetcher);
const [logInError, setLogInError] = useState(false);
const [email, onChangeEmail] = useInput('');
const [password, onChangePassword] = useInput('');
const onSubmit = useCallback( (e) => {
e.preventDefault();
setLogInError(false);
axios.post('/api/users/login',{ email, password },{ withCredentials: true})
.then(() => { mutate();})
.catch((error) => {
setLogInError(error.response?.data?.code === 401);
});
},
[email, password, mutate],

const onSubmit = useCallback(async (e) => {
e.preventDefault();
setLogInError(false);
const response = await login(email, password)
if (response.status === 200) {
window.open('/', '_self')
}
},
[email, password],
);

return (
Expand Down
51 changes: 46 additions & 5 deletions host/src/pages/Main/index.tsx
Original file line number Diff line number Diff line change
@@ -1,25 +1,66 @@
import React from 'react';
import { useEffect, useState } from "react";
import axios from "axios";
import { useRecoilState } from 'recoil';
import { userState } from "../../store/atoms";
import { loginsuccess, logout } from "@api/main"

const Main = () => {
const [isLogin, setIsLogin] = useState(false);
const [user, setUser] = useRecoilState(userState);

const Menu = React.lazy(() =>
// @ts-ignore
import("remote/Menu").then((module) => {return {default: module.Menu};
import("remote/Menu").then((module) => {
return { default: module.Menu };
})
);

useEffect(() => {
(async () => {
const { data } = await loginsuccess();
try {
if (data) {
setIsLogin(true);
setUser({ email: data.email, username: data.username });
}
} catch (error) {
console.log(error);
}
})();
}, []);


const logoutPage = async () => {
const data = await logout();
if (data.status === 200) {
window.open("/login", "_self");
}

};

return (
<div className="App">
<div> 여기가 Host </div>
<div> AOCE </div>
<div>
<a href="/signup">회원가입</a>
<a href="/login">로그인</a>
{/* <p>Name: {user.email}</p>
<p>Age: {user.username}</p> */}
<div>
{isLogin && <div>
<button onClick={logoutPage} className="loginButton">
Logout
</button>
</div>}
{!isLogin &&
<div>
<a href="/signup">회원가입</a>
<a href="/login">로그인</a>
</div>
}
</div>
<div>
<React.Suspense fallback={<div>Loading...</div>}>
<Menu/>
<Menu />
</React.Suspense>
</div>
</div>
Expand Down
12 changes: 12 additions & 0 deletions host/src/store/atoms.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { atom, RecoilEnv } from "recoil";
RecoilEnv.RECOIL_DUPLICATE_ATOM_KEY_CHECKING_ENABLED = false;

export const countState = atom({
key: "countState",
default: 0
});

export const userState = atom({
key: 'user',
default: { email: '[email protected]', username: 'aluminum' }
});
1 change: 1 addition & 0 deletions host/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
"@pages/*": ["pages/*"],
"@utils/*": ["utils/*"],
"@hooks/*": ["hooks/*"],
"@api/*": ["api/*"]
}
},
"include": [
Expand Down
3 changes: 3 additions & 0 deletions remote/config-overrides.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@ module.exports = function (config, env) {
new ModuleFederationPlugin(
(module.exports = {
name: "remote",
remotes: {
host: `host@http://localhost:3000/remoteEntry.js`,
},
exposes: {
"./Menu": "./src/components/Menu"
},
Expand Down
1 change: 1 addition & 0 deletions remote/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
"react-dom": "^18.2.0",
"react-error-boundary": "^3.1.4",
"react-scripts": "5.0.1",
"recoil": "^0.7.7",
"styled-components": "^5.3.8"
},
"scripts": {
Expand Down
14 changes: 9 additions & 5 deletions remote/src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
import { RecoilRoot } from 'recoil';

function App() {
return (
<div className="App">
<header className="App-header" data-e2e="REMOTE_COMPONENT_INFO">
Remote Application
</header>
</div>
<RecoilRoot>
<div className="App">
<header className="App-header" data-e2e="REMOTE_COMPONENT_INFO">
Remote Application
</header>
</div>
</RecoilRoot>
);
}

Expand Down
30 changes: 30 additions & 0 deletions remote/src/components/Maps/LeftModal.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import React from "react";
import { useRecoilState, useResetRecoilState, useRecoilValue } from "recoil";
import { userState } from "host/atoms";
import { countState } from "host/atoms";

export const Counter = () => {
const [count, setCount] = useRecoilState(countState);
const user = useRecoilValue(userState);
const resetCount = useResetRecoilState(countState);

const increase = () => {
setCount(count + 1);
};

const reset = () => {
resetCount();
};

return (
<div>
<div>
<div>{user.email}</div>
<div>{user.username}</div>
</div>
<h2>{count}</h2>
<button onClick={() => increase()}>+</button>
Copy link
Contributor

Choose a reason for hiding this comment

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

<button onClick={increase}>+</button>

<button onClick={() => reset()}>reset</button>
Copy link
Contributor

Choose a reason for hiding this comment

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

<button onClick={resetCount}>reset</button>

</div>
);
};
15 changes: 9 additions & 6 deletions remote/src/components/Menu.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import styled from 'styled-components';

import Maps from 'components/Maps/Maps';
import { MixedBoundary } from 'components/Common';
import { Counter } from './Maps/LeftModal';

export const Menu = () => {
const Div = styled.div`
Expand All @@ -10,11 +10,14 @@ export const Menu = () => {
`;
// let MapsComponent = React.lazy(() => import('./components/Maps'));
return (
<Div>
<MixedBoundary>
<Maps />
</MixedBoundary>
</Div>
<div style = {{display : "flex"}}>
<Counter/>
<Div>
<MixedBoundary>
<Maps />
</MixedBoundary>
</Div>
</div>
);
};
export default Menu;