State Management

Context API

Context provides a way to pass data through the component tree without having to pass props down manually at every level.

SWR

SWR is a popular library used for data fetching and state management in React applications. Data fetching is covered in Axios API calls section, here we are going to cover about state management using SWR.

Materially is managing state of following using SWR

  1. Snackbar states

  2. Menu states

1. Snackbar

Snackbar is used to show notification in application. Whenever component dispatch a action with data to show snackbar, it appears in app. The initial state of snackbar is being capture using useSWR hooks and after that, we are mutating it state based on action calls. Following is the initital state:

This values has been inititilised using useSWR like below:

src/states/snackbar.ts
const initialState: SnackbarProps = {
  action: false,
  open: false,
  message: 'Note archived',
  anchorOrigin: { vertical: 'bottom', horizontal: 'right' },
  alert: { severity: 'success', variant: 'filled' },
  variant: 'default',
  transition: 'Fade',
  close: false
};

Now, how to read these values and update as well.

To read the values and listen, following the SWR hooks is sufficient in the component. Whenever any changes happen, it is activated like a redux selector and acts based on logic.

src/components/Snackbar.tsx
...
import { closeSnackbar, useGetSnackbar } from 'api/snackbar';
...

// ==============================|| SNACKBAR ||============================== //

const Snackbar = () => {
  const { snackbar } = useGetSnackbar();
  ...
  ...
};

export default Snackbar;

To open the Snack bar, we need to change the value and mutate the state. Here is how it is done

src/states/snackbar.ts
export function openSnackbar(snackbar: SnackbarProps) {
  // to update local state based on key

  const { action, open, message, anchorOrigin, alert, variant, transition, close } = snackbar;

  mutate(
    endpoints.key,
    (currentSnackbar: SnackbarProps | undefined) => {
      return {
        ...currentSnackbar,
        action: action || initialState.action,
        open: open || initialState.open,
        message: message || initialState.message,
        anchorOrigin: anchorOrigin || initialState.anchorOrigin,
        alert: {
          severity: alert?.severity || initialState.alert.severity,
          variant: alert?.variant || initialState.alert.variant
        },
        variant: variant || initialState.variant,
        transition: transition || initialState.transition,
        close: close || initialState.close
      };
    },
    false
  );
}

Last updated

Was this helpful?