Friday, March 24, 2023

React CRUD application using a useReducer hook for state management

 Step 1: First, we'll define our initial state and the action types that we'll use:

 

const initialState = {
  items: [],
};

const ADD_ITEM = "ADD_ITEM";
const DELETE_ITEM = "DELETE_ITEM";
const UPDATE_ITEM = "UPDATE_ITEM";
 

Step 2: Next, we'll define our reducer function:

 

function reducer(state, action) {
  switch (action.type) {
    case ADD_ITEM:
      return {
        ...state,
        items: [...state.items, action.payload],
      };
    case DELETE_ITEM:
      return {
        ...state,
        items: state.items.filter((item) => item.id !== action.payload),
      };
    case UPDATE_ITEM:
      return {
        ...state,
        items: state.items.map((item) =>
          item.id === action.payload.id ? action.payload : item
        ),
      };
    default:
      return state;
  }
}

In this reducer function, we handle three types of actions:

  • ADD_ITEM: adds a new item to the items array in state
  • DELETE_ITEM: removes an item from the items array in state based on its id
  • UPDATE_ITEM: updates an item in the items array in state based on its id

 Step 3: Now, let's create our main component, App, which will use the reducer to manage state:

function App() {
  const [state, dispatch] = useReducer(reducer, initialState);

  const addItem = (item) => {
    dispatch({ type: ADD_ITEM, payload: item });
  };

  const deleteItem = (id) => {
    dispatch({ type: DELETE_ITEM, payload: id });
  };

  const updateItem = (item) => {
    dispatch({ type: UPDATE_ITEM, payload: item });
  };

  return (
    <div>
      <ItemList items={state.items} deleteItem={deleteItem} updateItem={updateItem} />
      <AddItemForm addItem={addItem} />
    </div>
  );
}
 

In this App component, we use the useReducer hook to create a state object and a dispatch function to send actions to the reducer. We also define three callback functions (addItem, deleteItem, and updateItem) that will be passed down to child components.

 Step 4:Next, let's create the ItemList and AddItemForm components:

function ItemList({ items, deleteItem, updateItem }) {
  return (
    <ul>
      {items.map((item) => (
        <li key={item.id}>
          {item.name} ({item.quantity})
          <button onClick={() => deleteItem(item.id)}>Delete</button>
          <button onClick={() => updateItem(item)}>Edit</button>
        </li>
      ))}
    </ul>
  );
}

function AddItemForm({ addItem }) {
  const [name, setName] = useState("");
  const [quantity, setQuantity] = useState("");

  const handleSubmit = (event) => {
    event.preventDefault();
    const newItem = { name, quantity };
    addItem(newItem);
    setName("");
    setQuantity("");
  };

  return (
    <form onSubmit={handleSubmit}>
      <label>
        Name:
        <input type="text" value={name} onChange={(e) => setName(e.target.value)} />
      </label>
      <label>
        Quantity:
        <input type="number" value={quantity} onChange={(e) => setQuantity(e.target.value)} />
      </label>
      <button type="submit">Add Item</button>

 

augustine

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation.

0 comments:

Post a Comment

 

Copyright @ 2013 React Tutorials.

Designed by Mathew | mathai