0

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

4
  • 1
    In reducer function, don't enclose output of *.filter(...) in square brackets. filter returns an array, and you're creating array of array, which results in invalid data. Commented Jul 13, 2021 at 4:37
  • thanks,it worked.Can you propse a proper answer so that I can upvote it and someone else stuck can use it? Commented Jul 13, 2021 at 4:44
  • Use clientAccessGrants: [...state.clientAccessGrants.filter(item => item !== action.grant.api)] Commented Jul 13, 2021 at 4:48
  • @rudeTool Sure. posted. @Rahul no need to destructure it again since Array.filter(...) will create a new reference already. Commented Jul 13, 2021 at 7:07

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

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.