Skip to content

Commit

Permalink
add channelsApi
Browse files Browse the repository at this point in the history
  • Loading branch information
Tatyana-js committed Jan 5, 2025
1 parent a8ca384 commit 9540f35
Show file tree
Hide file tree
Showing 8 changed files with 100 additions and 62 deletions.
25 changes: 25 additions & 0 deletions frontend/src/api/channelsApi.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';


export const channelsApi = createApi({
reducerPath: 'channels',
baseQuery: fetchBaseQuery({
baseUrl: '/api/v1',
prepareHeaders: (headers) => {
const token = localStorage.getItem('token');
if (token) {
headers.set('Authorization', `Bearer ${token}`);
}
return headers;
}
}),
endpoints: (builder) => ({
getChannels: builder.query({
query: () => 'channels',
}),
}),
});

export const {
useGetChannelsQuery,
} = channelsApi;
68 changes: 35 additions & 33 deletions frontend/src/components/Сhannels.jsx
Original file line number Diff line number Diff line change
@@ -1,42 +1,44 @@
import { Nav } from 'react-bootstrap';
import axios from 'axios';
import { useEffect, useState } from 'react';
import router from '../utils/routes.js';

const getAuthHeader = () => {
const token = localStorage.getItem('token');
if (token) {
return { Authorization: `Bearer ${token}`};
}
return {};
};
import { Nav, Button } from 'react-bootstrap';
import { useGetChannelsQuery } from '../api/channelsApi.js';
import { useRef, useEffect } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { selectActiveTab, activeChannelSelector } from '../store/activeChannelSlice.js';

const Channels = () => {
const [channels, setChannels] = useState([]);
const { data, error, isLoading, refetch } = useGetChannelsQuery();
const dispatch = useDispatch();
const channels = data;
const channelsRef = useRef(null);
const activeChannel = useSelector(activeChannelSelector);
useEffect(() => {
const fetchContent = async () => {
const { data } = await axios.get(router.channelsPath(), { headers: getAuthHeader() });
console.log(data);
setChannels(data);
};

fetchContent();
}, []);
}, []);
console.log(channels);
console.log(activeChannel);

return (
<Nav as="ul" id="channels-box" className="flex-column nav-pills nav-fill px-2 mb-3 overflow-auto h-100 d-block">
<li className="nav-item w-100">
<button type="button" className="w-100 rounded-0 text-start btn btn-secondary">
<span className="me-1"># </span>
general
</button>
</li>
<li className="nav-item w-100">
<button type="button" className="w-100 rounded-0 text-start btn">
<span className="me-1"># </span>
random
</button>
</li>
<Nav
as="ul"
id="channels-box"
className="flex-column nav-pills nav-fill px-2 mb-3 overflow-auto h-100 d-block"
ref={channelsRef}
>
{channels?.map((channel) => {
return (
<Nav.Item as="li" key={channel.id} className="w-100">
<Button
type="button"
className="w-100 rounded-0 text-start"
variant={channel.id === activeChannel ? "secondary" : ""}
onClick={() => dispatch(selectActiveTab({ id: channel.id }))}
>
<span className="me-1"># </span>
{channel.name}
</Button>
</Nav.Item>
);
}
)}
</Nav>
);
};
Expand Down
5 changes: 4 additions & 1 deletion frontend/src/context/AuthProvider.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import useAuth from '../hooks/index.jsx';
// eslint-disable-next-line react/prop-types
const AuthProvider = ({ children }) => {
const [loggedIn, setLoggedIn] = useState(!!localStorage.getItem('token'));

const token = localStorage.getItem('token');

const logIn = (token, username) => {
localStorage.setItem('token', token);
Expand All @@ -18,6 +20,7 @@ const AuthProvider = ({ children }) => {
localStorage.removeItem('username');
setLoggedIn(false);
};

useEffect(() => {
const token = localStorage.getItem('token');
if (token) {
Expand All @@ -26,7 +29,7 @@ const AuthProvider = ({ children }) => {
}, []);

return (
<AuthContext.Provider value={{ loggedIn, logIn, logOut }}>
<AuthContext.Provider value={{ loggedIn, logIn, logOut, token }}>
{children}
</AuthContext.Provider>
);
Expand Down
3 changes: 0 additions & 3 deletions frontend/src/pages/LoginPage.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,7 @@ const LoginPage = () => {
setAuthFailed(false);
try {
const res = await axios.post(router.loginPath(), values);
localStorage.setItem('token', res.data.token);
localStorage.setItem('username', res.data.username);
auth.logIn(res.data.token, res.data.username);
console.log(auth.loggedIn);
navigate(router.main());
} catch (err) {
formik.setSubmitting(false);
Expand Down
19 changes: 19 additions & 0 deletions frontend/src/store/activeChannelSlice.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { createSlice } from '@reduxjs/toolkit';

const initialState = {
currentChannel: 1,
};

const activeChannelSlice = createSlice({
name: 'activeChannel',
initialState,
reducers: {
selectActiveTab: (state, { payload }) => {
state.activeChannel = payload;
},
},
});

export const activeChannelSelector = (state) => state.activeChannel.currentChannel;
export const { selectActiveTab } = activeChannelSlice.actions;
export default activeChannelSlice.reducer;
17 changes: 0 additions & 17 deletions frontend/src/store/channelsSlice.js

This file was deleted.

23 changes: 16 additions & 7 deletions frontend/src/store/index.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,17 @@
import { configureStore } from '@reduxjs/toolkit';
import channelsReducer from './channelsSlice';
import { combineReducers, configureStore } from '@reduxjs/toolkit';
import { channelsApi } from '../api/channelsApi.js';
import activeChannelReducer from './activeChannelSlice.js';

export default configureStore({
reducer: {
channels: channelsReducer,
}
});
const rootReducer = combineReducers({
[channelsApi.reducerPath]: channelsApi.reducer,
activeChannel: activeChannelReducer,
// messages: mesagesReducer,
});

const store = configureStore ({
reducer: rootReducer,
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware().concat(channelsApi.middleware),
});

export default store;
2 changes: 1 addition & 1 deletion frontend/vite.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ export default defineConfig({
// Проксируем запросы к API
'/api': {
target: 'http://127.0.0.1:5001',
// changeOrigin: true,
changeOrigin: true,
},
// Проксируем WebSocket соединения
'/socket.io': {
Expand Down

0 comments on commit 9540f35

Please sign in to comment.