I am trying to delete data from the table, and I don’t understand what I'm doing wrong. On the server, everything is normally deleted, and on the client I will see the updated label only after reloading the page. How can I make it clear to the client that I deleted it?
This is what action looks like:
import {DELETE_BOOK, FETCH_BOOK} from "../constants/constants"; import axios from 'axios' const apiUrl = 'http://localhost:4200/book/'; export const deleteBookSuccess = id => { return { type: DELETE_BOOK, payload: id } }; export const deleteBook = id => { return (dispatch) => { return axios.get(`${apiUrl}/delete/${id}`) .then(response => { dispatch(deleteBookSuccess(response.data)) }) .catch(error => { throw(error); }); }; }; reducer:
import {DELETE_BOOK} from "../constants/constants"; export default (state = [], action) => { switch (action.type){ case DELETE_BOOK: return state.filter(book => book._id !== action.payload.id); default: return state; } } import React, {Component, Fragment} from 'react' import {connect} from 'react-redux' import PropTypes from 'prop-types' import TableBooks from '../components/TableBooks' import {fetchAllBooks, deleteBook} from "../actions/books"; class StoreBooks extends Component { componentDidMount() { this.props.allBooks(); }; render() { return ( <Fragment> <TableBooks books={this.props.books} deleteBook={this.props.onDeleteBook}/> </Fragment> ) } } StoreBooks.propTypes = { books: PropTypes.array, allBooks: PropTypes.func.isRequired, onDeleteBook: PropTypes.func.isRequired }; const mapDispatchToProps = dispatch => { return { onDeleteBook: id => { dispatch(deleteBook(id)) }, allBooks: book => { dispatch(fetchAllBooks(book)) } } } const mapStateToProps = state => { return { books: state.books } }; export default connect(mapStateToProps, mapDispatchToProps)(StoreBooks) import React, {Fragment} from 'react' import TableRow from '../TableRow' const TableBooks = ({books, deleteBook}) => { const elements = books.map(book => { return ( <TableRow book={book} key={book._id} deleteBook={deleteBook}/> ) }); return ( <Fragment> <div className={"table-users"}> <div className={"header"}>Книги</div> <table cellSpacing="0" id="table-to-xls"> <tbody> <tr> <th>Название</th> <th>Автор</th> <th>Издательство</th> <th>Серия</th> <th width="230">Цена</th> </tr> {elements} </tbody> </table> </div> </Fragment> ) }; export default TableBooks import React from 'react' import {Link} from 'react-router-dom' const TableRow = ({book, deleteBook}) => { return ( <tr> <td> {book.titleBook} </td> <td> {book.authorBook} </td> <td> {book.publishing} </td> <td> {book.series} </td> <td>{book.price}</td> <td> <button><Link to={"/edit/" + book._id}>Редактировать</Link></button> </td> <td> <button onClick={() => deleteBook(book._id)}>Delete</button> </td> </tr> ) }; export default TableRow;
return state.filter(book => book._id !== action.payload.id);onreturn state.filter(book => book._id !== action.payload);and earn. - sneas