Friday, March 24, 2023

React CRUD application using the useReducer hook simple Example

Step 1: In this example, we define an initial state object that contains an empty array of items. 

Step 2: We also define a reducer function that handles the add, edit, and delete actions on the state. We use the useReducer hook to create a state object and a dispatch function that allows us to update the state by dispatching actions to the reducer function.

Step 3: The form in the render function allows us to add or edit items. When we submit the form, we dispatch an add or edit action to the reducer function, depending on whether we're adding a new item or editing an existing one. We also reset the name input field.

Step 4: The list of items is displayed as an unordered list. Each item is rendered as an li element with its name, an Edit button, and a Delete button. Clicking the Edit button sets the editItem state to the selected item and populates the name input field with its name. Clicking the Delete button dispatches a delete action to the reducer function with the item's ID as the payload.

Here is an example of a simple CRUD app that allows you to add, edit, and delete items in a list:

 

import React, { useReducer, useState } from 'react';

const initialState = {
  items: []
};

function reducer(state, action) {
  switch (action.type) {
    case 'add':
      return {
        items: [...state.items, action.payload]
      };
    case 'edit':
      return {
        items: state.items.map((item) => {
          if (item.id === action.payload.id) {
            return action.payload;
          }
          return item;
        })
      };
    case 'delete':
      return {
        items: state.items.filter((item) => item.id !== action.payload)
      };
    default:
      throw new Error();
  }
}

function App() {
  const [state, dispatch] = useReducer(reducer, initialState);
  const [name, setName] = useState('');
  const [editItem, setEditItem] = useState(null);

  const handleSubmit = (event) => {
    event.preventDefault();
    if (!name.trim()) {
      return;
    }
    if (editItem) {
      dispatch({ type: 'edit', payload: { ...editItem, name } });
      setEditItem(null);
    } else {
      dispatch({
        type: 'add',
        payload: { id: new Date().getTime(), name }
      });
    }
    setName('');
  };

  const handleEdit = (item) => {
    setEditItem(item);
    setName(item.name);
  };

  const handleDelete = (id) => {
    dispatch({ type: 'delete', payload: id });
  };
 
    return (
    <div>
      <h1>CRUD App</h1>
      <form onSubmit={handleSubmit}>
        <input
          type='text'
          placeholder='Enter name'
          value={name}
          onChange={(event) => setName(event.target.value)}
        />
        <button type='submit'>{editItem ? 'Edit' : 'Add'}</button>
      </form>
      <ul>
        {state.items.map((item) => (
          <li key={item.id}>
            {item.name}
            <button type='button' onClick={() => handleEdit(item)}>
              Edit
            </button>
            <button type='button' onClick={() => handleDelete(item.id)}>
              Delete
            </button>
          </li>
        ))}
      </ul>
    </div>
  );
}

export default App;


 

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