0

I am writing a crud application with react-redux, I have successfullly finished read, create, and update Now i am trying to learn implement delete operation and i found it is tricky though it is easiest one.

This is my table.js file:

import React, {Fragment} from "react";
import { connect } from "react-redux";

class Table extends React.Component {
    onEdit = (item) => {  //Use arrow function to bind `this`
        this.props.selectedData(item);
    }

    onDelete = (index) => {
        this.props.selectedData(index);
    }
    render() {
        return (
            <Fragment>
                <thead>
                    <tr>
                        <th scope="col">Name</th>
                        <th scope="col">Age</th>
                        <th scope="col">Email</th>
                        <th>Edit</th>
                    </tr>
                </thead>
                <tbody>
                {this.props.employees.map((item, index) => (
                    <tr key={index}>
                        <td>{item.name}</td>
                        <td>{item.age}</td>
                        <td>{item.email}</td>
                        <td>
                            <button
                                type="button"
                                onClick={() => this.onEdit(item)}>EDIT
                            </button>
                            <button
                                onClick={ () => this.onDelete(index) }>DELETE
                            </button>
                        </td>
                    </tr>
                ))}
                </tbody>
            </Fragment>
        );
    }
}

const mapStateToProps = (state) => ({ employees: state.employees });

export default connect(mapStateToProps)(Table);

and this is my form.js file

import React, { Fragment } from "react"
import { connect } from 'react-redux'

class Form extends React.Component {
  constructor(props) {
    super(props);
    this.state = { 
      id: this.props.selectedData.id, 
      name: this.props.selectedData.name, 
      age: this.props.selectedData.age, 
      email: this.props.selectedData.email 
    };
    this.onHandleChange = this.onHandleChange.bind(this);
    this.submit = this.submit.bind(this);
  }

  submit(event) {
    const data = {
      name: this.state.name, 
      age: this.state.age, 
      email: this.state.email
    };
    if (this.props.isEdit) {
      data.id = this.props.selectedData.id;
      console.log('edit', data);
      this.props.dispatch({ type: 'EDIT_POST', data })
    } else {
      // generate id here for new emplyoee
      this.props.dispatch({ type: 'ADD_POST', data })
    }
  }

  onHandleChange(event) {
    this.setState({
      [event.target.name]: event.target.value
    });
  }

  componentDidUpdate(prevProps) {
    if (prevProps.selectedData.email !== this.props.selectedData.email) {  //Check on email, because email is unique
      this.setState({ name: this.props.selectedData.name, age: this.props.selectedData.age, email: this.props.selectedData.email })
    }
  }



  render() {
    return (
      <form>
        <div className="form-group">
          <input onChange={(event) => this.onHandleChange(event)} value={this.state.name} name="name" type="text" />
        </div>

        <div className="form-group">
          <input onChange={(event) => this.onHandleChange(event)} value={this.state.age} name="age" type="number" />
        </div>

        <div className="form-group">
          <input onChange={(event) => this.onHandleChange(event)} value={this.state.email} name="email" type="text" />
        </div>

        <button onClick={(event) => this.submit(event)} type="button">
          {this.props.isEdit ? 'Update' : 'SAVE'}
        </button>

      </form>
    );
  }
}

export default connect(null)(Form);

and this is my postReducer.js file:

var initialState = {
  employees: [
    { id: 1, name: 'jhon', age: '23', email: 'a@a' }, 
    { id: 2, name: 'doe', age: '24', email: 'b@a' }
  ]
};

var postReducer = (state = initialState, action) => {
  switch (action.type) {
    case 'ADD_POST':
      return {
        ...state,
        employees: [...state.employees, action.data],
      };
    case 'EDIT_POST':
      return {
        ...state,
        employees: state.employees.map(emp => emp.id === action.data.id ? action.data : emp)
      };
    case 'DELETE_POST':
      return state.filter((post)=>post.id !== action.id);
    default:
      return state;
  }
};


export default postReducer;

and this is App.js file:

import React from "react"
import Table from "../components/table"
import Form from '../components/form'

class App extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
           selectedData: {name: '', age: '', email: ''},
           isEdit: false
        };
    }

    selectedData = (item) => {
       this.setState({selectedData: item,isEdit:true})
    }
    render() {
        return (
            <React.Fragment>   
              <Form selectedData={this.state.selectedData} isEdit={this.state.isEdit}/>          
            <table>
                <Table selectedData={this.selectedData} />
            </table>
            </React.Fragment>
        );
    }
}
export default App;

and this is my index.js file:

import React from "react";
import ReactDOM from "react-dom";

import App from "../src/components/App";

import { Provider } from 'react-redux'

import { createStore } from 'redux'
import postReducer from '../src/postReducer'

const store = createStore(postReducer)


// if we don't subcribe, yet our crud operation will work
function onStateChange() {
  const state = store.getState();
  console.log(JSON.stringify(state, null, 2));
}

store.subscribe(onStateChange)

ReactDOM.render((
  <Provider store={store}>
      <App />
  </Provider>
), document.getElementById('app'))

Everything is working great except delete operation, can anyone help me to achieve delete operation? I failed to implement delete operation only, it would be really much appreciated if anyone fix me delete operation

Thanks

4
  • can you give a minified example of the error, what is the error you are getting Commented Aug 18, 2019 at 17:53
  • you never dispatch the DELETE_POST action from the code above. what have you tried? Commented Aug 18, 2019 at 17:55
  • return state.filter((post)=>post.id !== action.id); should be return {...state, employees: state.employees.filter((post)=>post.id !== action.id)}; in the reducer Commented Aug 18, 2019 at 17:55
  • Not works yet, i dont know why Commented Aug 18, 2019 at 17:57

1 Answer 1

1

What i am thinking here the redux updates are seems to be not working due to shallow comparing. Try like this

return {
    ...state,
    employees: state.filter((post)=>post.id !== action.id);
  };
Sign up to request clarification or add additional context in comments.

7 Comments

Not works, problem with dispatch, Can you please check the dispatch?
this.props.dispatch({ type: 'DELETE_POST', id }) need to be call this function
when you are triggring delete button pass the id of post here
please let me know if issue is anymore
Yes, I did it but not works.. onDelete = (item) => { const data = { id: this.props.selectedData(item), } this.props.dispatch({ type: 'DELETE_POST', data }); }
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.