The best way to do CRUD in large-scale Next.js Projects with Redux Toolkit & Axios

Nadim Chowdhury - Dec 31 '23 - - Dev Community

When dealing with large-scale Next.js projects, using Redux Toolkit for state management and Axios for handling API requests is a common and effective combination. Below is a guide on how to implement CRUD operations in a large-scale Next.js project using Redux Toolkit and Axios.

Step 1: Set Up Your Project

Install the required packages:

npm install react-redux @reduxjs/toolkit axios
Enter fullscreen mode Exit fullscreen mode

Step 2: Configure Redux Toolkit

Create your Redux slices for managing state:

redux/slices/entitiesSlice.js

import { createSlice } from '@reduxjs/toolkit';

const entitiesSlice = createSlice({
  name: 'entities',
  initialState: [],
  reducers: {
    setEntities: (state, action) => {
      return action.payload;
    },
    addEntity: (state, action) => {
      state.push(action.payload);
    },
    updateEntity: (state, action) => {
      const { id, updatedEntity } = action.payload;
      const index = state.findIndex((entity) => entity.id === id);
      if (index !== -1) {
        state[index] = updatedEntity;
      }
    },
    removeEntity: (state, action) => {
      const idToRemove = action.payload;
      return state.filter((entity) => entity.id !== idToRemove);
    },
  },
});

export const { setEntities, addEntity, updateEntity, removeEntity } = entitiesSlice.actions;
export default entitiesSlice.reducer;
Enter fullscreen mode Exit fullscreen mode

redux/store.js

import { configureStore } from '@reduxjs/toolkit';
import entitiesReducer from './slices/entitiesSlice';

const store = configureStore({
  reducer: {
    entities: entitiesReducer,
    // Add other reducers as needed
  },
});

export default store;
Enter fullscreen mode Exit fullscreen mode

Step 3: Set Up Axios for API Requests

api.js

import axios from 'axios';

const instance = axios.create({
  baseURL: 'https://your-api-base-url.com/api', // Adjust the base URL as needed
});

export const getEntities = async () => {
  const response = await instance.get('/entities');
  return response.data;
};

export const createEntity = async (newEntity) => {
  const response = await instance.post('/entities', newEntity);
  return response.data;
};

export const updateEntityById = async (id, updatedEntity) => {
  const response = await instance.put(`/entities/${id}`, updatedEntity);
  return response.data;
};

export const deleteEntityById = async (id) => {
  const response = await instance.delete(`/entities/${id}`);
  return response.data;
};
Enter fullscreen mode Exit fullscreen mode

Step 4: Integrate with Next.js

pages/index.js

import { useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { setEntities, addEntity, updateEntity, removeEntity } from '../redux/slices/entitiesSlice';
import { getEntities, createEntity, updateEntityById, deleteEntityById } from '../api';

const Home = () => {
  const dispatch = useDispatch();
  const entities = useSelector((state) => state.entities);

  useEffect(() => {
    // Fetch entities on component mount
    getEntities().then((data) => dispatch(setEntities(data)));
  }, [dispatch]);

  const handleCreateEntity = async () => {
    const newEntity = { name: 'New Entity' };
    const createdEntity = await createEntity(newEntity);
    dispatch(addEntity(createdEntity));
  };

  const handleUpdateEntity = async (id, updatedName) => {
    const updatedEntity = { name: updatedName };
    const updatedData = await updateEntityById(id, updatedEntity);
    dispatch(updateEntity({ id, updatedEntity: updatedData }));
  };

  const handleDeleteEntity = async (id) => {
    await deleteEntityById(id);
    dispatch(removeEntity(id));
  };

  return (
    <div>
      <h1>Entity List</h1>
      {entities.map((entity) => (
        <div key={entity.id}>
          <span>{entity.name}</span>
          <button onClick={() => handleUpdateEntity(entity.id, prompt('Enter new name:', entity.name))}>Update</button>
          <button onClick={() => handleDeleteEntity(entity.id)}>Delete</button>
        </div>
      ))}
      <button onClick={handleCreateEntity}>Create Entity</button>
    </div>
  );
};

export default Home;
Enter fullscreen mode Exit fullscreen mode

Step 5: Run Your Next.js App

Ensure your development server is running:

npm run dev
Enter fullscreen mode Exit fullscreen mode

Visit http://localhost:3000 in your browser to see the CRUD functionality in action.

Conclusion

This example illustrates a basic implementation of CRUD operations in a large-scale Next.js project using Redux Toolkit for state management and Axios for API requests. Adapt the code to meet your specific project requirements, such as adding error handling, authentication, or pagination, based on your application needs.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player