Search code examples
javascripthtmlreactjsreduxreact-redux

Why onClick deleting all the items in the redux array in react.js?


I am working on a react app where I have implemented a onClick button but that onClick button is deleting all the elements in the redux store array even when I am trying to filter and delete.Here are my codes:

reducerFunction

case Actions.DELETE_API_GRANT:{
      return{
        ...state,clientAccessGrants:[state.clientAccessGrants.filter(item=>action.grant.api!==item.api)]
      }
    }

My UI Component:

     deleteApiGrants(grant)
  {
    this.props.deleteApiGrants(grant)
  }
    {this.props.clientAccessGrants.map((grant, index) => (
              console.log(grant.api),
              <tr key={grant.api+grant.group}>
                <td>{grant.api}</td>
                
                <td>{grant.group}</td>
                
                <td>
                  <div>
                    <input type='button' value="delete" className='btn' onClick={()=>this.deleteApiGrants({api:grant.api,group:grant.group})}></input>
                    
                  </div>
                </td>
                </tr>

My array object structure is:

{
api:"something",
group:"something"
}

My map and dispatch function:

const mapDispatchToProps = (dispatch) => ({

  deleteApiGrants:(grant)=>dispatch(onDeleteApiGrant(grant))
});


 const mapStateToProps = (state) => ({

  clientAccessGrants:state.client.clientAccessGrants
});

My ActionCreator:

export function onDeleteApiGrant(grant)
{
  console.log(grant)
  return {type:Actions.DELETE_API_GRANT,grant}
}

Any help will highly appreciated.

Thanks


Solution

  • You need to correct your reducerFunction to this:

    case Actions.DELETE_API_GRANT:{
          return{
            // remove square brackets
            ...state,clientAccessGrants: state.clientAccessGrants.filter(item=>action.grant.api!==item.api)
          }
        }
    

    Reasoning

    From Array.prototype.filter() - JavaScript | MDN,

    Return value

    A new array with the elements that pass the test. If no elements pass the test, an empty array will be returned.