Home>

Reduce separately

const defaultState= {
    customers: []
  }
  export const customersReducer= (state= defaultState, action)= >
 {
    switch (action.type) {
      case 'addCustomer':
        return {... state, customers: [... state.customers, action.payload]}
      case 'removeCustomer':
        return {... state, customers: state.customers.filter (customer= >
 customer.id!== action.payload)}
      default:
        return state
    }
  }

Code:

const App= ()= >
 {
  const dispatch= useDispatch ();
  const customers= useSelector (state= >
state.customers.customers)
  const addCustomer= (name)= >
 {
    const customer= {
      name,
      id: Date.now (),
    }
    dispatch ({type: 'addCustomer', payload: customer})
  }
  const removeCustomer= (customer)= >
 {
    dispatch ({type: 'removeCustomer', payload: customer.id})
  }
  return (
    <
div style= {{display: 'flex', justifyContent: 'center', flexDirection: 'column'}} >
      <
div style= {{display: 'flex', justifyContent: 'center', margin: '20px 0'}} >
        <
div >
          <
button onClick= {()= >
addCustomer (prompt ())} >
Add client <
/button >
        <
/div >
      <
/div >
      {customers.length >
 0?
        <
div >
            {customers.map (customer= >
              <
div onClick= {()= >
removeCustomer ()} >
{customer.name} <
/div >
            )}
        <
/div >
        :
        <
div style= {{display: 'flex', justifyContent: 'center'}} >
          No clients
        <
/div >
      }
    <
/div >
  );
};
export default App;

Please clarify your specific problem or provide more detailed information on what exactly you need. As it stands, it is difficult to know exactly what you are asking.

Дух сообщества2021-12-20 13:15:06
  • Answer # 1

    Pass to the function when calling the customer itself

    <
    div >
       {customers.map (customer= >
          <
    div onClick= {()= >
    removeCustomer (customer)} >
    {customer.name} <
    /div >
       )}
    <
    /div >
    
  • Answer # 2

    Pass to the function when calling the customer itself

    <
    div >
       {customers.map (customer= >
          <
    div onClick= {()= >
    removeCustomer (customer)} >
    {customer.name} <
    /div >
       )}
    <
    /div >