Skip to content

Instantly share code, notes, and snippets.

@AlbertProfe
Last active April 19, 2024 10:55
Show Gist options
  • Save AlbertProfe/14c6b72614b80cd26e039e2775f534dc to your computer and use it in GitHub Desktop.
Save AlbertProfe/14c6b72614b80cd26e039e2775f534dc to your computer and use it in GitHub Desktop.
Reducers examples

Reducer examples

Counter

const complexCounterReducer = (state, action) => {
  switch (action.type) {
    case 'INCREMENT':
      return {
        ...state,
        count: state.count + 1,
        history: [...state.history, { action: 'INCREMENT', timestamp: Date.now() }]
      };
    case 'DECREMENT':
      return {
        ...state,
        count: state.count - 1,
        history: [...state.history, { action: 'DECREMENT', timestamp: Date.now() }]
      };
    case 'RESET':
      return {
        ...state,
        count: 0,
        history: []
      };
    default:
      return state;
  }
};

Todo

const todoReducer = (state, action) => {
  switch (action.type) {
    case 'ADD_TODO':
      return [...state, { id: action.id, text: action.text, completed: false }];
    case 'TOGGLE_TODO':
      return state.map(todo =>
        todo.id === action.id ? { ...todo, completed: !todo.completed } : todo
      );
    case 'REMOVE_TODO':
      return state.filter(todo => todo.id !== action.id);
    default:
      return state;
  }
};

Authentication

const authReducer = (state, action) => {
  switch (action.type) {
    case 'LOGIN':
      return { isAuthenticated: true, user: action.user };
    case 'LOGOUT':
      return { isAuthenticated: false, user: null };
    default:
      return state;
  }
};

Authentication with Loading

const authWithLoadingReducer = (state, action) => {
  switch (action.type) {
    case 'LOGIN_REQUEST':
      return {
        ...state,
        isLoading: true
      };
    case 'LOGIN_SUCCESS':
      return {
        ...state,
        isAuthenticated: true,
        user: action.user,
        isLoading: false
      };
    case 'LOGIN_FAILURE':
      return {
        ...state,
        isAuthenticated: false,
        error: action.error,
        isLoading: false
      };
    case 'LOGOUT':
      return {
        ...state,
        isAuthenticated: false,
        user: null
      };
    default:
      return state;
  }
};

Cart shooping

const cartReducer = (state, action) => {
  switch (action.type) {
    case 'ADD_ITEM':
      return [...state, action.item];
    case 'REMOVE_ITEM':
      return state.filter(item => item.id !== action.id);
    case 'UPDATE_QUANTITY':
      return state.map(item =>
        item.id === action.id ? { ...item, quantity: action.quantity } : item
      );
    case 'CLEAR_CART':
      return [];
    default:
      return state;
  }
};

Form

const formReducer = (state, action) => {
  switch (action.type) {
    case 'INPUT_CHANGE':
      return {
        ...state,
        [action.field]: action.value
      };
    case 'RESET_FORM':
      return action.initialState;
    default:
      return state;
  }
};

Pagination

const paginationReducer = (state, action) => {
  switch (action.type) {
    case 'SET_PAGE':
      return {
        ...state,
        currentPage: action.page
      };
    case 'SET_TOTAL_PAGES':
      return {
        ...state,
        totalPages: action.totalPages
      };
    default:
      return state;
  }
};

Fetching data

const dataReducer = (state, action) => {
  switch (action.type) {
    case 'FETCH_REQUEST':
      return {
        ...state,
        isLoading: true
      };
    case 'FETCH_SUCCESS':
      return {
        ...state,
        isLoading: false,
        data: action.payload
      };
    case 'FETCH_ERROR':
      return {
        ...state,
        isLoading: false,
        error: action.error
      };
    default:
      return state;
  }
};

Messenger

export function messengerReducer(state, action) {
  switch (action.type) {
    case 'changed_selection': {
      return {
        ...state,
        selectedId: action.contactId,
      };
    }
    case 'edited_message': {
      return {
        ...state,
        messages: {
          ...state.messages,
          [state.selectedId]: action.message,
        },
      };
    }
    case 'sent_message': {
      return {
        ...state,
        messages: {
          ...state.messages,
          [state.selectedId]: '',
        },
      };
    }
    default: {
      throw Error('Unknown action: ' + action.type);
    }
  }
}

Transfer

const initialState = {
  bankAccountFrom: null,
  bankAccountTo: null,
  value: null,
  date: null,
  currency: null,
  typeTransfer: null,
  status: "idle", // can be "request", "success", "failure", "reject", "pending"
  error: null
};

const transferReducer = (state, action) => {
  switch (action.type) {
    case "TRANSFER_REQUEST":
      return {
        ...state,
        status: "request",
        error: null
      };
    case "TRANSFER_SUCCESS":
      return {
        ...state,
        status: "success",
        error: null
      };
    case "TRANSFER_FAILURE":
      return {
        ...state,
        status: "failure",
        error: action.payload
      };
    case "TRANSFER_REJECT":
      return {
        ...state,
        status: "reject",
        error: action.payload
      };
    case "TRANSFER_PENDING":
      return {
        ...state,
        status: "pending",
        error: null
      };
    default:
      return state;
  }
};

export { transferReducer, initialState };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment