Skip to content

Commit

Permalink
final one task in create Thunk
Browse files Browse the repository at this point in the history
  • Loading branch information
ExLuZiVe53 committed Oct 27, 2023
1 parent 3bdff48 commit ae706e4
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 36 deletions.
15 changes: 3 additions & 12 deletions src/pages/PostDetailsPage.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,19 +7,12 @@ import {
useLocation,
useParams,
} from 'react-router-dom';
// import PostCommentsPage from './PostCommentsPage';

import Loader from 'components/Loader';
import ErrorMessage from 'components/ErrorMessage';

import { findPostById } from 'services/api';
import { useDispatch, useSelector } from 'react-redux';
import {
addPost,
requestPostDetails,
setError,
setIsLoading,
setPostDetails,
} from 'redux/postDetailReducer';
import { requestPostDetails } from 'redux/postDetailReducer';

const PostCommentsPage = lazy(() => import('pages/PostCommentsPage'));

Expand All @@ -28,6 +21,7 @@ const PostDetailsPage = () => {
const location = useLocation();
const backLinkHref = useRef(location.state?.from ?? '/');

// пілписка на дані зі стору
const postDetails = useSelector(state => state.postDetails.postDetailsData);
const isLoading = useSelector(state => state.postDetails.isLoading);
const error = useSelector(state => state.postDetails.error);
Expand All @@ -46,9 +40,6 @@ const PostDetailsPage = () => {
return (
<div>
<Link to={backLinkHref.current}>Go Back</Link>
<button onClick={() => dispatch(addPost({ title: '123', body: '123' }))}>
Click to add post to STATE
</button>

{isLoading && <Loader />}
{error && <ErrorMessage message={error} />}
Expand Down
35 changes: 11 additions & 24 deletions src/redux/postDetailReducer.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,15 @@ export const requestPostDetails = createAsyncThunk(
async (postId, thunkApi) => {
try {
// setIsLoading(true);

// робимо мережевий запит
const postData = await findPostById(postId);
// setPostDetails(postData);
return postData; // БУЛЕ ЗАПИСАНО В action.payload
} catch (error) {
// setError(error.message);
// після неуспішного запиту ми повернемо thunkApi та викличемо спецільний метод rejectWithValue і передамо об'єкт помилки
return thunkApi.rejectWithValue(error.message);
// rejected - виникне тільки коли ми руками переведемо проміс
}
}
);
Expand All @@ -39,42 +40,28 @@ const postDetailsSlice = createSlice({
// Початковий стан редюсера слайсу
initialState: INITIAL_STATE,
// Об'єкт редюсерів
reducers: {
setIsLoading(state, action) {
state.isLoading = action.payload;
},
setPostDetails(state, action) {
state.postDetailsData = action.payload;
},
setError(state, action) {
state.error = action.payload;
},
addPost(state, action) {
// state.posts.push(action.payload);
state.posts = [...state.posts, action.payload];
},
deletePost(state, action) {
state.posts = state.posts.filter(post => post.id !== action.payload);
// const deletedPostIndex = state.posts.findIndex(post => post.id === action.payload);
// state.posts.splice(deletedPostIndex, 1);
},
},
// !========================REDUX BLL======================
// thunk повертає спеціальні ред'юсери які отримують builder.addCase(назва thunk)
extraReducers: builder =>
builder
// PENDING - стан очікування запиту
.addCase(requestPostDetails.pending, (state, action) => {
state.isLoading = true;
state.error = null;
})
// FULFILED - запит пройшов успішно, та повернув дані
.addCase(requestPostDetails.fulfilled, (state, action) => {
state.isLoading = false;
// в Reducer дані потрапляють тільки через один спосіб action.payload
state.postDetailsData = action.payload;
})
// REJECTED - виникла помилка під час запиту
.addCase(requestPostDetails.rejected, (state, action) => {
state.isLoading = false;
state.error = action.payload;
}),
// !======================End/ REDUX BLL====================
});

// Генератори екшенів
export const { setIsLoading, setPostDetails, setError, addPost, deletePost } =
postDetailsSlice.actions;
// Редюсер слайсу
export const postDetailsReducer = postDetailsSlice.reducer;

0 comments on commit ae706e4

Please sign in to comment.