tim_woods
tim_woods

Reputation: 417

React and Redux: Onclick Delete Button Returning Undefined

In my code below, I have a delete button that should be deleting the data if clicked. However, when I click on it, I am seeing through console.log that it is returning undefined instead of the id number. Can't seem to figure out why. Any help will be greatly appreciated. Thank you.

//Actions File

export const GET_ITEMS           = 'GET ITEMS';
export const FETCH_ITEMS_SUCCESS = 'FETCH ITEMS SUCCESS';
export const FETCH_ITEMS_ERROR   = 'FETCH ITEMS ERROR';
export const DELETE_ITEM         = 'DELETE_ITEM';

    export const getItems = () => ({
      type: GET_ITEMS
    });
    
    export const deleteItem = (itemId) => ({
      type   : DELETE_ITEM,
      payload: itemId
    });

//App.js

    class App extends Component {
      componentDidMount() {
        this.props.getItems()
      }
    
    static propTypes = {
      getItems: PropTypes.func.isRequired,
      deleteItem: PropTypes.func.isRequired
    }
    handleDelete = (id) =>{
      this.props.deleteItem(id)
      console.log(this.props.deleteItem(id));
    }
    
    
      render() {
    const { itemsList} = this.props.items
        return (
          <div className="container app-wrapper">
            <header>
            {itemsList.map(item => (<h1 key={item.id}>{item.title} <button onClick={this.handleDelete.bind(this, item.id)}>delete</button></h1>))}
            </header>
          </div>
        );
      }
    }
    
    const mapStateToProps = state => ({
      items: state.items
    });
    export default connect(mapStateToProps, {getItems, deleteItem})(App);

Upvotes: 1

Views: 485

Answers (2)

user14361391
user14361391

Reputation:

You are referencing your delete action incorrectly in connect. deleteItem expects an id param passed into it.

Try this,

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

const mapDispatchToProps = (dispatch) =>
{
    return {
        deleteItem: (id) => dispatch(actions.deleteItem(id)),
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(App);

Upvotes: 0

Brian Thompson
Brian Thompson

Reputation: 14365

The dispatched action should return undefined, because it does not return anything. You are misunderstanding how data flows in the Redux/reducer pattern.

Here's the basic flow of a Redux update:

  1. Action is dispatched.
  2. All reducers receive the action object.
  3. All reducers return their new or previous state depending on that action's contents.
  4. connect sees that the Redux state has changed, and triggers a re-render of the children components.
  5. You may now use the updated data from your Redux store through props (mapped in mapStateToProps).

You cannot call an action and receive the updated state as the return value. It breaks the fundamental pattern of how data flows/updates in Redux.

Upvotes: 2

Related Questions