CRUD с Redux(JS) - реализация добавления, удаления, изменения данных на стороннем API
Коллеги, кто может помочь с реализацией добавления, удаления, изменения данных на стороннем API? Получил массив данных, который рендерится, и теперь необходимо добавить функционал добавления, удаления и изменения полученных данных. Как прописать редюсеры, actions, операции и разметку?
**файл fetch.js**
const BASE_URL = 'https://jsonplaceholder.typicode.com';
const fetchAllPosts = () => {
return fetch(`${BASE_URL}/posts`).then(response => {
return response.json();
});
};
const fetchCommentsToPosts = id => {
return fetch(`${BASE_URL}/posts/${id}/comments`).then(response => {
return response.json();
});
};
const fetchPostsById = id => {
return fetch(`${BASE_URL}/posts/${id}`).then(response => {
return response.json();
});
};
const addPost = post => {
return fetch(`${BASE_URL}/posts`, {
method: 'POST',
body: JSON.stringify(post),
headers: {
'Content-type': 'application/json; charset=UTF-8',
},
}).then(response => {
return response.json();
});
};
const updPost = (update, id) => {
return fetch(`${BASE_URL}/posts/${id}`, {
method: 'PATCH',
body: JSON.stringify(update),
headers: {
'Content-type': 'application/json; charset=UTF-8',
},
}).then(response => {
return response.json();
});
};
const deletePost = id => {
return fetch(`${BASE_URL}/posts/${id}`, {
method: 'DELETE',
}).then(response => {
return response.json();
});
};
**файл operations.js**
import { fetchAllPosts } from '../../fetch/fetch';
import actions from './actions';
export const fetchPosts = () => async dispatch => {
dispatch(actions.fetchPostRequest());
try {
const posts = await fetchAllPosts();
dispatch(actions.fetchPostSuccess(posts));
} catch (error) {
dispatch(actions.fetchPostError(error));
}
};
**файл actions.js**
import { createAction } from '@reduxjs/toolkit';
const fetchPostRequest = createAction('fetchPostRequest');
const fetchPostSuccess = createAction('fetchPostSuccess');
const fetchPostError = createAction('fetchPostError');
const filterItem = createAction('filter');
export default { filterItem, fetchPostRequest, fetchPostSuccess, fetchPostError };
**файл store.js**
import { configureStore } from '@reduxjs/toolkit';
import { combineReducers } from 'redux';
import { createReducer } from '@reduxjs/toolkit';
import actions from './actions';
const postReducer = createReducer([], {
[actions.fetchPostSuccess]: (_, action) => action.payload,
});
const filterReducer = (state = '', { type, payload }) => {
switch (type) {
case 'filter':
return payload;
default:
return state;
}
};
const rootReducer = combineReducers({
posts: postReducer,
filteredPosts: filterReducer,
});
const store = configureStore({
reducer: rootReducer,
});
export default store;
**файл postlist.js**
import { useEffect } from 'react';
import * as operations from '../redux/operations';
import { useDispatch, useSelector } from 'react-redux';
import Post from './post';
import s from './postList.module.css';
export default function PostList() {
const posts = useSelector(state => state.posts);
const dispatch = useDispatch();
useEffect(() => {
dispatch(operations.fetchPosts());
}, [dispatch]);
return (
<div>
{posts.length > 0 && (
<ul>
{posts.map(post => (
<li key={post.id}>
<Post title={post.title} body={post.body} />
</li>
))}
</ul>
)}
</div>
);
}
**файл post.js**
export default function Post({ title, body }) {
return (
<div className={s.postCard}>
<h2>{title}</h2>
<p>{body}</p>
</div>
);
}