React-Redux Part Three
So far with this small series of our simple to-do app, we have successfully implemented redux to our react application fetching data using Axios from our rails API backend. We have also been able to create new tasks to add to our list. We will now move on to deleting any task that we don't want in our list or if the user is done with it they can just delete it too.
Lets begin with our reducers. Go to the src/reducers/listReducers.js file and add a case for deleteting a task. The following will be our entire switch case :
export default (state=[],action)=>{switch(action.type){case 'FETCH_LIST':return [...state, ...action.payload]case 'CREATE_TASK':return [...state, action.payload]case 'DELETE_TASK':return state.filter(task=> task.id !== action.payload)default:return state}}
In the case that the action type is DELETE_TASK we will filter through the state and return all tasks that does not equal to the action payload which will eventually be the id of the task we will want to delete. We use the filter method in this case because when using redux we don't want to mutate our data and in this case the filter method will not mutate the array of the state.
Ok great! Let’s move on to our actions. Go to the src/actions/index.js file. We will create an action using Axios to delete a specific task from our list. We will allow this action to accept an argument of the id. So we will have the following:
export const deleteTask=(id)=>{return async (dispatch)=>{await api.delete(`/lists/${id}`)dispatch({type:'DELETE_TASK', payload:id})}}
And lets finally put it all together and make a button, so when the user clicks on that button it will delete it. In our src/components/Showlist.js file we will import our deleteTask action that we just created and use it in our buttons onClick handler. We will have the following in our ShowList file:
import React from 'react';import {fetchList, deleteTask} from '../actions/index'import {connect} from 'react-redux'class ShowList extends React.Component {componentDidMount(){this.props.fetchList()}renderList=()=>{return this.props.list.map(l=>{return(<div key={l.id}><button onClick={()=>this.props.deleteTask(l.id)}>X</button> {l.task} </div>)})}render(){return (<>{this.renderList()}</>)}}const mapStateToProps=(state)=>{return {list:Object.values(state.list)}}export default connect(mapStateToProps,{fetchList, deleteTask})(ShowList);
Awesome we completed our delete function! We should have something that looks like this: