How to use use-immer - 8 common examples

To help you get started, we’ve selected a few use-immer examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github uyuni-project / uyuni / web / html / src / manager / content-management / shared / components / panels / sources / channels / channels-selection.js View on Github external
const ChannelsSelection = (props: PropsType) => {
  const {fetchChannelsTree, isChannelsTreeLoaded,channelsTree }: UseChannelsType = useChannelsTreeApi();
  const {fetchMandatoryChannelsByChannelIds, isDependencyDataLoaded, requiredChannelsResult}= useMandatoryChannelsApi();
  const [state, dispatchChannelsSelection] : [StateChannelsSelectionType, (ActionChannelsSelectionType) => void]
    = useImmerReducer(
    (draft, action) => reducerChannelsSelection(draft, action, channelsTree, requiredChannelsResult),
    initialStateChannelsSelection(props.initialSelectedIds),
  );

  const isAllApiDataLoaded = isChannelsTreeLoaded && isDependencyDataLoaded;

  useEffect(() => {
    fetchChannelsTree()
      .then((channelsTree: ChannelsTreeType) => {
        fetchMandatoryChannelsByChannelIds({channels: Object.values(channelsTree.channelsById)});
      })
  }, [])

  useEffect(() => {
    // set lead base channel as first and notify
    const sortedSelectedChannelsId = state.selectedChannelsIds
github mattblackdev / react-entity-component-system / src / useEntityComponentSystem.js View on Github external
export function useEntityComponentSystem(
  initialEntities = [],
  systems = [],
  {
    initializeEntities = defaultInitializeEntities,
    getUniqueId = defaultUniqueId,
    renderEntities = defaultRenderEntities,
    debug = false,
  } = {},
) {
  const [entities, updateEntities] = useImmer({})

  const warnIfEntitiesUpdatedMoreThanTwoRendersInARow = useConsoleWarnIfInvokedTooManyRendersInARow(
    2,
    `Entities initialized more than 2 renders in a row.
    You may want to wrap them in React.useState or move the array outside of the component using useEntityComponentSystem.`,
  )
  React.useEffect(() => {
    debug && console.debug('Initialilizing entities')
    warnIfEntitiesUpdatedMoreThanTwoRendersInARow()
    updateEntities(() => initializeEntities(initialEntities, getUniqueId))
  }, [
    initialEntities,
    initializeEntities,
    updateEntities,
    getUniqueId,
    warnIfEntitiesUpdatedMoreThanTwoRendersInARow,
github ra-gg / Delir / packages / delir / src / utils / hooks.ts View on Github external
export const useObjectState = (initialState: T) => {
  const [state, update] = useImmer(initialState)

  const updater = useCallback((part: Partial | ((draft: Draft) => Partial)) => {
    update(draft => {
      if (typeof part === 'function') {
        Object.assign(draft, part(draft))
      } else {
        Object.assign(draft, part)
      }
    })
  }, [])

  return [state, updater] as const
}
github Dreamacro / clash-dashboard / src / lib / hook.ts View on Github external
export function useObject (initialValue: T) {
    const [copy, rawSet] = useImmer(initialValue)

    function set> (key: K, value: Draft[K]): void
    function set> (data: Partial): void
    function set> (f: (draft: Draft) => void | T): void
    function set> (data: any, value?: Draft[K]): void {
        if (typeof data === 'string') {
            rawSet(draft => {
                const key = data as K
                const v = value
                draft[key] = v
            })
        } else if (typeof data === 'function') {
            rawSet(data)
        } else if (typeof data === 'object') {
            rawSet((draft: Draft) => {
                const obj = data as Draft
github sthobis / sleddit / src / components / Sidebar.tsx View on Github external
const Sidebar = ({
  isSidebarOpened,
  activeSubreddit,
  isRedditBlocked,
  savedSubreddits
}: SidebarProps) => {
  const [subreddits, updateSubreddits] = useImmer(savedSubreddits);
  const [subredditInput, setSubredditInput] = useState("");
  const [subredditInputHasFocus, setSubredditInputHasFocus] = useState(
    false
  );

  const subredditInputRef = useRef();

  const focusSubredditInput = () => {
    if (subredditInputRef.current) {
      subredditInputRef.current.focus();
    }
  };

  const handleChange = (e: ChangeEvent) => {
    setSubredditInput((e.target.value || "").toLowerCase());
  };
github inkandswitch / pushpin / src / background / components / FeedView.tsx View on Github external
function useFeedInfo(feedId: string): FeedInfo {
  const feed = useFeed(feedId)
  const [info, update] = useImmer({
    writable: false,
    downloaded: 0,
    total: 0,
    blocks: [],
  })

  useEffect(() => {
    if (!feed) return () => {}

    function setTotals(info: FeedInfo) {
      if (!feed) return
      info.total = feed.length
      info.downloaded = feed.downloaded()
    }

    function onReady() {
github datenguide / datenguide / src / pages / detail.js View on Github external
const Detail = ({ initialStatistics, initialRegions, initialError }) => {
  const classes = useStyles()

  const [state, dispatch] = useImmerReducer(reducer, {
    regions: initialRegions,
    statistics: initialStatistics,
    error: initialError
  })

  const { regions, statistics, error } = state

  return (
github mashabow / bezier-smoothness / src / store.tsx View on Github external
export const Provider: React.FC = ({ children }) => {
  const [state, dispatch] = useImmerReducer(reducer, initialState);
  return (
    {children}
  );
};

use-immer

Use immer with React hooks

MIT
Latest version published 1 year ago

Package Health Score

62 / 100
Full package analysis