Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Snyk] Upgrade @reduxjs/toolkit from 1.2.5 to 1.3.0 #69

Merged
merged 1 commit into from
Apr 18, 2020

Conversation

snyk-bot
Copy link
Contributor

Snyk has created this PR to upgrade @reduxjs/toolkit from 1.2.5 to 1.3.0.

ℹ️ Keep your dependencies up-to-date. This makes it easier to fix existing vulnerabilities and to more quickly identify and fix newly disclosed vulnerabilities when they affect your project.
  • The recommended version is 14 versions ahead of your current version.
  • The recommended version was released 23 days ago, on 2020-03-24.
Release notes
Package name: @reduxjs/toolkit
  • 1.3.0 - 2020-03-24

    This release adds two new APIs: createEntityAdapter to help manage normalized state, and createAsyncThunk to abstract common data fetching behavior.

    It also improves bundle size by inlining some of our prior dependencies and fixing cases where dev APIs were accidentally being included in production, as well as using a new version of Immer that tree-shakes better.

    Finally, we've improved the developer experience by tweaking our TS typings for better inference and updating the dev check middleware to warn if checks are taking too much time.

    New APIs

    One of the primary goals for Redux Toolkit has always been to simplify common use cases and reduce "boilerplate" by providing APIs that can replace code you were previously writing out by hand.

    To that end, v1.3.0 adds two new APIs for the common use cases of async data fetching and managing normalized data in the store.

    createAsyncThunk

    The Redux docs have taught that async logic should typically dispatch "three-phase async actions" while doing data fetching: a "start" action before the request is made so that loading UI can be displayed, and then a "success" or "failure" action to handle loading the data or showing an error message. Writing these extra action types is tedious, as is writing thunks that dispatch these actions and differ only by what the async request is.

    Given that this is a very common pattern, we've added a createAsyncThunk API that abstracts this out. It accepts a base action type string and a callback function that returns a Promise, which is primarily intended to be a function that does a data fetch and returns a Promise containing the results. It then auto-generates the request lifecycle action types / creators, and generates a thunk that dispatches those lifecycle actions and runs the fetching callback.

    From there, you can listen for those generated action types in your reducers, and handle loading state as desired.

    createEntityAdapter

    The Redux docs have also advised storing data in a "normalized" state shape, which typically means keeping each type of item in a structure that looks like {ids: [], entities: {} }. However, the Redux core provides no APIs to help manage storing and updating your data using this approach. Many community libraries exist, with varying tradeoffs, but so far we haven't officially recommended any of them.

    Caching data is a hard problem, and not one that we are interested in trying to solve ourselves. However, given that we do recommend this specific pattern, and that Redux Toolkit is intended to help simplify common use cases, we want to provide a minimal set of functionality to help users manage normalized state.

    To help solve this, we've specifically ported the @ngrx/entity library to work with Redux Toolkit, with some modifications.

    The core API function is createEntityAdapter. It generates a set of reducer functions and selectors that know how to work with data that has been stored in that normalized {ids: [], entities: {} } format, and can be customized by passing in a function that returns the ID field for a given item. If you want to keep the item IDs in a sorted order, a comparison function can also be passed in.

    The returned EntityAdapter object contains generated CRUD functions for manipulating items within that state, and generated selector functions that know how to read from that state. You can then use the generated CRUD functions and selectors within your own code.

    There is one very important difference between RTK's implementation and the original @ngrx/entity implementation. With @ngrx/entity, methods like addOne(item, state) accept the data argument first and the state second. With RTK, the argument order has been flipped, so that the methods look like addOne(state, item), and the methods can also accept a standard Redux Toolkit PayloadAction containing the data as the second argument. This allows them to be used as Redux case reducers directly, such as passing them in the reducers argument for createSlice. They can also be used as "mutating" helper functions inside createReducer and createSlice as well, thanks to use of Immer internally.

    Documentation

    We've added new API reference and usage guide sections to the Redux Toolkit docs to cover these new APIs:

    Bundle Size Improvements and Dependency Updates

    Immer 6.0

    Immer has always been the largest chunk of code added to your bundle from using RTK. Until now, RTK specifically depended on Immer 4.x, since 5.x added support for handling Maps and Sets (which aren't useful in a Redux app) and that support added to its bundle size.

    Immer's code was written in a way that kept it from tree-shaking properly. Fortunately, Immer author Michel Weststrate put in some amazing work refactoring the code to better support tree-shaking, and his efforts are now available as Immer 6.0.

    Per the Immer documentation on customizing Immer's capabilities, Immer now uses a plugin architecture internally, and additional functionality has to be explicitly enabled as an opt-in. There are currently three Immer plugins that can be enabled: ES5 support (for environments without ES6 Proxies), Map/Set support, and JSON Patch support.

    Redux Toolkit force-enables ES5 support. This is because we expect RTK to be used in multiple environments that do not support Proxies, such as Internet Explorer and React Native. It's also how Immer previously behaved, so we want to keep that behavior consistent and not break code given that this is a minor release of RTK. (In a hypothetical future major release, we may stop force-enabling the ES5 plugin and ask you to do it if necessary.)

    Overall, this should drop a couple KB off your app's minified bundle size.

    You may choose to enable the other plugins in your app code if that functionality is desired.

    Store Configuration Dependencies

    Since its creation, RTK has depended on leoasis/redux-immutable-state-invariant to throw errors if accidental mutations are detected, and the zalmoxisus/redux-devtools-extension NPM package to handle setup and configuration of the Redux DevTools Extension as the store is created.

    Unfortunately, neither of these dependencies is currently published as ES Modules, and we recently found out that the immutable middleware was actually being included in production bundles despite our attempts to ensure it is excluded.

    Given that the repo for the immutable middleware has had no activity in the last 3 years, we've opted to fork the package and include the code directly inside Redux Toolkit. We've also inlined the tiny-invariant and json-stringify-safe packages that the immutable middleware depended on.

    The DevTools setup package, while tiny, suffers from the same issue, and so we've forked it as well.

    Based on tests locally, these changes should reduce your production bundle sizes by roughly 2.5K minified.

    During the development process, we found that the serializable invariant middleware was partly being included in production. We've decided that both the immutable and serializable middleware should always be no-ops in prod if they're ever included, both to ensure minimum bundle size, and to eliminate any unwanted slowdowns.

    Other Changes

    Type Inference Improvements

    Users reported that it was possible to pass an entity adapter update method as a case reducer even if the slice state type didn't match what the update method expected (#434 ). We've updated the TS types to prevent that from being possible.

    We've also had a number of cases where users had issues with the typings for action payloads depending on whether strictNullChecks: false was set. We've altered our action creator types to improve that behavior.

    Dev Check Middleware Timings

    The immutability and serializability dev check middleware both do deep checks of state on every dispatch in dev mode. With a large state tree, this can sometimes noticeably slow down the app, and it's not immediately clear that the dev check middleware are responsible for this.

    We've updated both middleware to record how much time is spent actually performing the state checks, and they will now log warning messages if the checks take too long to give you a heads-up that you might want to alter the middleware settings or disable them entirely. The delay is configurable, and defaults to 32ms (two UI frames).

    In addition, the serializable middleware now ignores meta.args in every action by default. This is because createAsyncThunk automatically takes any arguments to its payload creator function and inserts them into dispatched actions. Since a user may be reasonably passing non-serializable values as arguments, and they're not intentionally inserting those into actions themselves, it seems sensible to ignore any potential non-serializable values in that field.

    TypeScript Support

    We've dropped support for TS versions earlier than 3.5. Given that 3.8 is out, this shouldn't be a major problem for users.

    Meanwhile, we've also re-exported the TS types from Reselect for convenience.

    Example Usage

    This example demonstrates the typical intended usage of both createEntityAdapter and createAsyncThunk.

    import { createAsyncThunk, createSlice, unwrapResult, createEntityAdapter } from '@reduxjs/toolkit'
    import { userAPI } from './userAPI'
    

    const fetchUserById = createAsyncThunk(
    'users/fetchByIdStatus',
    async (userId) => {
    const response = await userAPI.fetchById(userId)
    return response.data
    }
    )

    const usersAdapter = createEntityAdapter()

    const usersSlice = createSlice({
    name: 'users',
    initialState: usersAdapter.getInitialState({
    loading: 'idle',
    error: null
    }),
    reducers: {
    usersLoaded: usersAdapter.setAll,
    userDeleted: usersAdapter.removeOne,
    },
    extraReducers: {
    [fetchUserById.pending]: (state, action) => {
    if (state.loading === 'idle') {
    state.loading = 'pending'
    }
    },
    [fetchUserById.fulfilled]: (state, action) => {
    if (state.loading === 'pending') {
    state.loading = 'idle'
    usersAdapter.addOne(state, action.payload)
    }
    },
    [fetchUserById.rejected]: (state, action) => {
    if (state.loading === 'pending') {
    state.loading = 'idle'
    state.error = action.error
    }
    }
    }
    })

    const UsersComponent = () => {
    const { users, loading, error } = useSelector(state => state.users)
    const dispatch = useDispatch()

    const fetchOneUser = async userId => {
    try {
    const resultAction = await dispatch(fetchUserById(userId))
    const user = unwrapResult(resultAction)
    showToast('success', </span>Fetched <span class="pl-s1"><span class="pl-pse">${</span><span class="pl-smi">user</span>.<span class="pl-c1">name</span><span class="pl-pse">}</span></span><span class="pl-pds">)
    } catch (err) {
    showToast('error', </span>Fetch failed: <span class="pl-s1"><span class="pl-pse">${</span><span class="pl-smi">err</span>.<span class="pl-smi">message</span><span class="pl-pse">}</span></span><span class="pl-pds">)
    }
    }

    // render UI here
    }

    Thanks

    We'd like to thank the many people who contributed and made this release possible:

    • @jonjaques : created the initial version of createAsyncThunk that we based our implementation on
    • The entire NgRx team, particularly @brandonroberts and @MikeRyanDev , for creating @ngrx/entity and allowing us to port it to Redux Toolkit
    • @phryneas: our resident TS wizard, who made innumerable improvements to the TS behavior and createAsyncThunk implementation
    • @msutkowski : lots of feedback on the error handling design for createAsyncThunk
    • @Ethan-Arrowood: pointed us to a novel technique he'd developed for optional overriding of TS generic arguments
    • @mweststrate: the creator of Immer, who made massive improvements to its tree shaking and bundle size capabilities, published a utility for tracking tree shaking sizes of exports, and kept in touch with us on the status of Immer 6
    • All the users who actually tried out the alphas and betas and gave us feedback on bug reports and API design.

    Changelog

    For the complete set of code changes, see:

    and this diff:

    v1.2.5...v1.3.0

    For the iterative changes as this release was developed, see the Releases page for the individual release notes.

  • 1.3.0-beta.1 - 2020-03-21

    This release improves type inference for action creators and for entity adapters that are used as reducers, adds warnings if dev check middleware are taking excessive amounts of time, and adds a new selectById entity selector.

    Changes

    Type Inference Improvements

    Users reported that it was possible to pass an entity adapter update method as a case reducer even if the slice state type didn't match what the update method expected (#434 ). We've updated the TS types to prevent that from being possible.

    We've also had a number of cases where users had issues with the typings for action payloads depending on whether strictNullChecks: false was set. We've altered our action creator types to improve that behavior.

    Meanwhile, we've also re-exported the TS types from Reselect for convenience.

    Dev Check Middleware Timings

    The immutability and serializability dev check middleware both do deep checks of state on every dispatch in dev mode. With a large state tree, this can sometimes noticeably slow down the app, and it's not immediately clear that the dev check middleware are responsible for this.

    We've updated both middleware to record how much time is spent actually performing the state checks, and they will now log warning messages if the checks take too long to give you a heads-up that you might want to alter the middleware settings or disable them entirely. The delay is configurable, and defaults to 32ms (two UI frames).

    Entity Adapter API Changes

    We've added a selectById selector to createEntityAdapter for convenience.

    We've also removed the map() update method, which accepted a callback that returned changes to be applied. It couldn't be used as a reducer (the action would be non-serializable), it's easily re-implemented in userland using the updateMany() update method, and the name map implied a potentially completely different return type of a non-mutating copy, which is not what it actually did.

    Changelog

    • Feature/entity selectors (@markerikson - #440)
    • prevent any-casting of S generic on entityAdapter reducer-like f… (@phryneas - #436)
    • simplify signatures of ActionCreatorWithOptionalPayload (@phryneas - #428)
    • display a warning if immutableStateInvariantMiddleware (@phryneas - #427)

    v1.3.0-beta.0...v1.3.0-beta.1

  • 1.3.0-beta.0 - 2020-03-05

    This release adds two new APIs: createEntityAdapter to help manage normalized state, and createAsyncThunk to abstract common data fetching behavior.

    It also improves bundle size by fixing cases where APIs were accidentally being included in production and inlining some of our prior dependencies, as well as using a new version of Immer that tree-shakes better.

    Note: this is a beta release. We feel that the APIs are stable and are hopefully ready for a final release soon, and they have been documented and tested. However, we'd still like some additional feedback from users before publishing a final release.

    Please comment in issue #373: Roadmap: RTK v1.3.0 with any feedback on using these new APIs.

    This version is available as @reduxjs/toolkit@beta on NPM, or @reduxjs/[email protected].

    New APIs

    createAsyncThunk

    The Redux docs have taught that async logic should typically dispatch "three-phase async actions" while doing data fetching: a "start" action before the request is made so that loading UI can be displayed, and then a "success" or "failure" action to handle loading the data or showing an error message. Writing these extra action types is tedious, as is writing thunks that dispatch these actions and differ only by what the async request is.

    Given that this is a very common pattern, we've added a createAsyncThunk API that abstracts this out. It accepts a base action type string and a callback function that returns a Promise, which is primarily intended to be a function that does a data fetch and returns a Promise containing the results. It then auto-generates the request lifecycle action types / creators, and generates a thunk that dispatches those lifecycle actions and runs the fetching callback.

    From there, you can listen for those generated action types in your reducers, and handle loading state as desired.

    createEntityAdapter

    The Redux docs have also advised storing data in a "normalized" state shape, which typically means keeping each type of item in a structure that looks like {ids: [], entities: {} }. However, the Redux core provides no APIs to help manage storing and updating your data using this approach. Many community libraries exist, with varying tradeoffs, but so far we haven't officially recommended any of them.

    Caching data is a hard problem, and not one that we are interested in trying to solve ourselves. However, given that we do recommend this specific pattern, and that Redux Toolkit is intended to help simplify common use cases, we want to provide a minimal set of functionality to help users manage normalized state.

    To help solve this, we've specifically ported the @ngrx/entity library to work with Redux Toolkit, with some modifications.

    The core API function is createEntityAdapter. It generates a set of reducer functions and selectors that know how to work with data that has been stored in that normalized {ids: [], entities: {} } format, and can be customized by passing in a function that returns the ID field for a given item. If you want to keep the item IDs in a sorted order, a comparison function can also be passed in.

    The returned EntityAdapter object contains generated CRUD functions for manipulating items within that state, and generated selector functions that know how to read from that state. You can then use the generated CRUD functions and selectors within your own code.

    There is one very important difference between RTK's implementation and the original @ngrx/entity implementation. With @ngrx/entity, methods like addOne(item, state) accept the data argument first and the state second. With RTK, the argument order has been flipped, so that the methods look like addOne(state, item), and the methods can also accept a standard Redux Toolkit PayloadAction containing the data as the second argument. This allows them to be used as Redux case reducers directly, such as passing them in the reducers argument for createSlice. They can also be used as "mutating" helper functions inside createReducer and createSlice as well, thanks to use of Immer internally.

    Documentation

    See our beta API reference and usage guide docs for details:

    Bundle Size Improvements and Dependency Updates

    Immer 6.0

    Immer has always been the largest chunk of code added to your bundle from using RTK. Until now, RTK specifically depended on Immer 4.x, since 5.x added support for handling Maps and Sets (which aren't useful in a Redux app) and that support added to its bundle size.

    Immer's code was written in a way that kept it from tree-shaking properly. Fortunately, Immer author Michel Weststrate put in some amazing work refactoring the code to better support tree-shaking, and his efforts are now available as Immer 6.0.

    Per the Immer documentation on customizing Immer's capabilities, Immer now uses a plugin architecture internally, and additional functionality has to be explicitly enabled as an opt-in. There are currently three Immer plugins that can be enabled: ES5 support (for environments without ES6 Proxies), Map/Set support, and JSON Patch support.

    Redux Toolkit force-enables ES5 support. This is because we expect RTK to be used in multiple environments that do not support Proxies, such as Internet Explorer and React Native. It's also how Immer previously behaved, so we want to keep that behavior consistent and not break code given that this is a minor release of RTK. (In a hypothetical future major release, we may stop force-enabling the ES5 plugin and ask you to do it if necessary.)

    Overall, this should drop a couple KB off your app's minified bundle size.

    You may choose to enable the other plugins in your app code if that functionality is desired.

    Store Configuration Dependencies

    Since its creation, RTK has depended on leoasis/redux-immutable-state-invariant to throw errors if accidental mutations are detected, and the zalmoxisus/redux-devtools-extension NPM package to handle setup and configuration of the Redux DevTools Extension as the store is created.

    Unfortunately, neither of these dependencies is currently published as ES Modules, and we recently found out that the immutable middleware was actually being included in production bundles despite our attempts to ensure it is excluded.

    Given that the repo for the immutable middleware has had no activity in the last 3 years, we've opted to fork the package and include the code directly inside Redux Toolkit. We've also inlined the tiny-invariant and json-stringify-safe packages that the immutable middleware depended on.

    The DevTools setup package, while tiny, suffers from the same issue, and so we've forked it as well.

    Based on tests locally, these changes should reduce your production bundle sizes by roughly 2.5K minified.

    Changes since Alpha

    This beta release has a few additional changes since the 1.3.0-alpha.10 release.

    createAsyncThunk Error Handling Improvements

    We've spent a lot of time going over the error handling semantics for createAsyncThunk to ensure that errors can be handled outside the thunk, be correctly typed, and that validation errors from a server can be processed correctly. We also now detect if AbortController is available in the environment, and if not, provide a tiny polyfill that suggests adding a real polyfill to your application.

    See PR #393: createAsyncThunk: reject with typed value for much of the discussion and work, as well as the API reference docs.

    Middleware Updates

    We found that the serializable invariant middleware was partly being included in production. We've decided that both the immutable and serializable middleware should always be no-ops in prod, both to ensure minimum bundle size, and to eliminate any unwanted slowdowns.

    In addition, the serializable middleware now ignores meta.args in every action by default. This is because createAsyncThunk automatically takes any arguments to its payload creator function and inserts them into dispatched actions. Since a user may be reasonably passing non-serializable values as arguments, and they're not intentionally inserting those into actions themselves, it seems sensible to ignore any potential non-serializable values in that field.

    Immer 6 final

    We've updated Immer 6 from an alpha build to its final 6.0.1 release. This fixes the ability to use RTK with TS 3.5 and 3.6, as Immer has re-added typings support for those TS versions.

    Other Changes

    TypeScript Support

    We've dropped support for TS versions earlier than 3.5. Given that 3.8 is out, this shouldn't be a major problem for users.

    Example Usage

    This example demonstrates the typical intended usage of both createEntityAdapter and createAsyncThunk.

    import { createAsyncThunk, createSlice, unwrapResult, createEntityAdapter } from '@reduxjs/toolkit'
    import { userAPI } from './userAPI'
    

    const fetchUserById = createAsyncThunk(
    'users/fetchByIdStatus',
    async (userId, { getState }) => {
    const { loading } = getState().users
    if (loading !== 'idle') {
    return
    }
    const response = await userAPI.fetchById(userId)
    return response.data
    }
    )

    const usersAdapter = createEntityAdapter()

    const usersSlice = createSlice({
    name: 'users',
    initialState: usersAdapter.getInitialState({
    loading: 'idle',
    error: null
    }),
    reducers: {
    usersLoaded: usersAdapter.setAll,
    userDeleted: usersAdapter.removeOne,
    },
    extraReducers: {
    [fetchUserById.pending]: (state, action) => {
    if (state.loading === 'idle') {
    state.loading = 'pending'
    }
    },
    [fetchUserById.fulfilled]: (state, action) => {
    if (state.loading === 'pending') {
    state.loading = 'idle'
    usersAdapter.addOne(state, action.payload)
    }
    },
    [fetchUserById.rejected]: (state, action) => {
    if (state.loading === 'pending') {
    state.loading = 'idle'
    state.error = action.error
    }
    }
    }
    })

    const UsersComponent = () => {
    const { users, loading, error } = useSelector(state => state.users)
    const dispatch = useDispatch()

    const fetchOneUser = async userId => {
    try {
    const resultAction = await dispatch(fetchUserById(userId))
    const user = unwrapResult(resultAction)
    showToast('success', </span>Fetched <span class="pl-s1"><span class="pl-pse">${</span><span class="pl-smi">user</span>.<span class="pl-c1">name</span><span class="pl-pse">}</span></span><span class="pl-pds">)
    } catch (err) {
    showToast('error', </span>Fetch failed: <span class="pl-s1"><span class="pl-pse">${</span><span class="pl-smi">err</span>.<span class="pl-smi">message</span><span class="pl-pse">}</span></span><span class="pl-pds">)
    }
    }

    // render UI here
    }

    Changelog

    Changes since alpha.10:

    Changes since alpha.10:

    v1.3.0-alpha.10...v1.3.0-beta.0

    All 1.3 changes:

    v1.2.5...v1.3.0-beta.0

  • 1.3.0-alpha.10 - 2020-02-27

    This release reduces bundle sizes by updating to the latest Immer 6 alpha to help reduce bundle sizes and inlining the nanoid dependency.

    Note: Due to the Immer upgrade, this RTK alpha version requires at least TypeScript 3.7 if you are consuming it in a TypeScript app. The final version of RTK 1.3 will hopefully support TS 3.5+ once immerjs/immer#541 has been merged in.

    Changes

    Bundle Size Improvements

    Immer has always been the largest chunk of code added to your bundle from using RTK. Until now, RTK specifically depended on Immer 4.x, since 5.x added support for handling Maps and Sets (which aren't useful in a Redux app) and that support added to its bundle size.

    Immer's code was written in a way that kept it from tree-shaking properly. Fortunately, Immer author Michel Weststrate has been hard at work refactoring the code to better support tree-shaking, and his effort are now available as Immer 6.x alpha.

    Per the updated Immer alpha installation docs, Immer now uses a plugin architecture internally, and additional functionality has to be explicitly enabled as an opt-in. There are currently three Immer plugins that can be enabled: ES5 support (for environments without ES6 Proxies), Map/Set support, and JSON Patch support.

    In this alpha, Redux Toolkit force-enables ES5 support. This is because we expect RTK to be used in multiple environments that do not support Proxies, such as Internet Explorer and React Native. It's also how Immer previously behaved, so we want to keep that behavior consistent and not break code given that this is a minor release of RTK. (In a hypothetical future major release, we may stop force-enabling the ES5 plugin and ask you to do it if necessary.)

    Overall, this should drop a couple KB off your app's minified bundle size.

    You may choose to enable the other plugins in your app code if that functionality is desired.

    Inlined nanoid

    We received reports that the nanoid library, which we used for generating unique request IDs in createAsyncThunk, prints warnings on React Native due to a lack of crypto availability. Since we don't need anything cryptographically secure, just reasonably random, we've inlined the function from nanoid/no-secure and dropped the nanoid dependency.

    Documentation

    We've added TypeScript usage guides for createAsyncThunk and createEntityAdapter to the alpha docs:

    Alpha docs: createAsyncThunk and createEntityAdapter TypeScript usage guide

    Changelog

    v1.3.0-alpha.9...v1.3.0-alpha.10

  • 1.3.0-alpha.9 - 2020-02-21

    This release reduces bundle sizes by forking and inlining the redux-immutable-state-invariant and redux-devtools-extension dependencies, and modifies the types for createEntityAdapter.

    Changes

    Dependency Updates and Bundle Size

    Since its creation, RTK has depended on leoasis/redux-immutable-state-invariant to throw errors if accidental mutations are detected, and the zalmoxisus/redux-devtools-extension NPM package to handle setup and configuration of the Redux DevTools Extension as the store is created.

    Unfortunately, neither of these dependencies is currently published as ES Modules, and we recently found out that the immutable middleware was actually being included in production bundles despite our attempts to ensure it is excluded.

    Given that the repo for the immutable middleware has had no activity in the last 3 years, we've opted to fork the package and include the code directly inside Redux Toolkit. We've also inlined the tiny-invariant and json-stringify-safe packages that the immutable middleware depended on.

    The DevTools setup package, while tiny, suffers from the same issue, and so we've forked it as well.

    Based on tests locally, these changes should reduce your production bundle sizes by roughly 2.5K minified.

    As a future note, Immer is currently being reworked to enable better shakeability, and once that is released, we plan on updating RTK to use the new Immer version as well. This is unlikely to make it into RTK 1.3.0, but we'll put out another update once we've been able to confirm that the changes work for us.

    createEntityAdapter Types

    We made a few more tweaks to the type definitions for createEntityAdapter. Shouldn't be anything breaking, but clarifying the possible overloads for the generated methods.

    Changelog

    v1.3.0-alpha.8...v1.3.0-alpha.9

  • 1.3.0-alpha.8 - 2020-02-19

    This release fixes a couple edge case bugs with entity update operations, and documents expected update behavior. Also, since the new APIs look to be somewhat stabilized, we've merged the original PR into a v1.3.0 tracking branch where we can integrate additional planned changes.

    Roadmap

    We've put up a v1.3.0 roadmap issue to track other planned work before 1.3.0 is released.

    Changes

    createEntityAdapter Update Logic

    We identified a couple potential bugs and edge cases inside the updateMany method implementation. We've fixed a potential issue that might have appeared when multiple updates were passed in attempting to rename the same entity to different IDs in a row, fixed a wrong type definition for comparer callbacks, and documented expected behavior when ID renames do occur.

    Documentation

    The alpha docs are available at https://deploy-preview-374--redux-starter-kit-docs.netlify.com/. In particular, see the API references for:

    Changelog

    v1.2.5...v1.3.0-alpha.8

  • 1.3.0-alpha.7 - 2020-02-18

    This release reworks the cancellation functionality in createAsyncThunk.

    Changes

    createAsyncThunk cancellation

    We previously added AbortController support to createAsyncThunk, to allow other code to trigger whatever cancellation might be applicable to the async logic inside.

    The thunk now exits early when the abort() method is called and doesn't keep waiting for the payloadCreator to finish. This should be an improvement especially in cases where the payloadCreator didn't care about the abort signal, but something outside was awaiting the promise from dispatch.

    Also, before this, a non-signal-aware payloadCreator could still finish which would have caused a dispatch of a "fulfilled" action after an "rejected" (abort) action, which was confusing.

    We've also removed the meta.abortReason property as it's no longer possible to override the error in the "rejected" action.

    Changelog

    v1.3.0-alpha.6...v1.3.0-alpha.7

  • 1.3.0-alpha.6 - 2020-02-17

    This release alters the internal behavior of the createEntityAdapter CRUD methods to allow them to work as "mutating helper functions" when not directly used as case reducers, and adds initial API reference documentation for createEntityAdapter.

    Changes

    createEntityAdapter and Immer

    The original version of createEntityAdapter that we ported from the @ngrx/entity library used hand-written immutable update logic internally. We replaced that with use of Immer, as it made it consistent with how createReducer and createSlice work, and simplified some of the logic.

    Previously, the CRUD methods such as addOne() always called Immer's createNextState() internally to wrap the updating logic. This worked okay when the CRUD method was used as a case reducer directly.

    However, when called manually as a helper function inside an existing case reducer, the behavior was confusing. The case reducer had already received state as an Immer Draft value, but that draft was being passed into createNextState again. In theory, updates to the nested draft are supposed to propagate back to the parent draft, but we didn't see updates propagating upwards as expected.

    We've updated the CRUD methods to first check whether the incoming state value is an Immer Draft, or just a plain JS value. If it's already a Draft, we pass that draft to the mutating internal update logic, so the changes are applied correctly. If it's a plain object, we still call createNextState() and return a plain value.

    So, when using the CRUD methods as helper functions, treat them as mutating the existing state value:

    const booksSlice = createSlice({
        name: "books",
        initialState: booksAdapter.getInitialState({totalBooks: 0),
        reducers: {
            bookAdded(state, action) {
                // Ignore return value here, and "mutate" state
                booksAdapter.addOne(state, action.payload.book)
                // can continue to mutate state here
                state.totalBooks++
            }
        }
    })

    Documentation

    A first draft of API documentation for createEntityAdapter is now available:

    createEntityAdapter draft API reference

    Changelog

    v1.3.0-alpha.5...v1.3.0-alpha.6

  • 1.3.0-alpha.5 - 2020-02-16

    This release reworks the createAsyncThunk types to enable more flexibility in declaring optional generic arguments.

    Changes

    createAsyncThunk Generic Types

    Per notes in alpha.4, our original types made it actually impossible to declare the correct State type for use by getState in your promise payload creator callback.

    We came up with a stopgap solution, but since TS doesn't allow you to specify individual generic arguments by name, it meant that specifying types for some of the thunk options might require specifying all generic types whether you wanted to or not.

    Fortunately, @Ethan-Arrowood has found a novel technique for optionally overriding specific generics by name, in a syntax similar to object destructuring, and we've been able to apply that here.

    Per the previous example, the most common use case for createAsyncThunk still does not require specifying any types by hand, as the types for the Returned value and the thunkArg argument will be inferred from your payload creator callback:

    // basic usage:
    const thunk1 = createAsyncThunk("a", async (arg: string) => {
        return 42
    })

    To specify the type of State, you'll need to specifically declare the types of Returned and thunkArg. Then, pass in an object as the third generic argument, and declare the type of a field named state inside that object:

    // specify state type for getState usage
    const thunk2 = createAsyncThunk<Promise<number>, string, {state: RootState}>(
        "a",
        async (arg: string, {getState}) => {
            const state = getState();
            return 42;
        }
    )

    If you only want to declare the type of the extra thunk argument, do the same thing, but override the extra field instead of state:

    interface UserAPI {
      fetchUserById: (id: number) => Promise<User>
    }
    // specify state type for getState usage
    const thunk2 = createAsyncThunk<Promise<User>, string, {extra: UserAPI}>(
        "a",
        async (arg: string, {extra}) => {
            const user = await extra.fetchUserById(123)
            return user;
        }
    )

    Previously, that would have required also declaring the type of the state generic, since state was listed before extra in the generics definition.

    Changelog

    v1.3.0-alpha.4...v1.3.0-alpha.5

  • 1.3.0-alpha.4 - 2020-02-16

    This alpha release rearranges the TS generic types of createAsyncThunk to fix broken usage.

    Changes

    createAsyncThunk Types

    createAsyncThunk gives you access to getState in the thunkAPI object argument. However, we hadn't tried to exercise that yet in our tests, and it turns out there was no valid way to specify the correct type of the state returned by getState.

    We've rearranged the generic types and tweaked the defaults. You should now be able to use it without specifying any generics for the most common case (returning a value, with a potential argument for the payload callback), and specify three types if you need to declare what the state type is:

    // basic usage:
    const thunk1 = createAsyncThunk("a", async (arg: string) => {
        return 42
    })
    // infers: return = Promise<number>, arg = string
    

    // specify state type for getState usage
    const thunk2 = createAsyncThunk<Promise<number>, string, RootState>(
    "a",
    async (arg: string, {getState}) => {
    const state = getState();
    return 42;
    }
    )
    // declared: return = Promise<number>, arg = string, state: RootState

    We have some ideas for additional potential improvements to these types that may make usage simpler, so please keep an eye out for further alpha releases.

    Documentation

    A first draft of API documentation for createAsyncThunk is now available:

    createAsyncThunk draft API reference

    Changes

    v1.3.0-alpha.3...v1.3.0-alpha.4

    See PR #352: Port ngrx/entity and add createAsyncThunk for the complete alpha changes.

  • 1.3.0-alpha.3 - 2020-02-15
  • 1.3.0-alpha.2 - 2020-02-15
  • 1.3.0-alpha.1 - 2020-02-14
  • 1.3.0-alpha.0 - 2020-02-12
  • 1.2.5 - 2020-02-13
from @reduxjs/toolkit GitHub release notes
Commit messages
Package name: @reduxjs/toolkit
  • f14c0dc 1.3.0
  • a1e8bec v1.3.0 Integration (#374)
  • de26824 Reorder installation sections and add to readme for consistency (#433)
  • 84483e6 Remove the cd/start commands (#423)
  • 1b78aeb Attempted Netlify tweaks (#422)
  • f4f63f4 Add "Create a React Redux App" to quick start (#419)
  • d2f2a51 Update intermediate-tutorial.md (#405)
  • ae39737 fixed the spelling of the word `attached` (#403)
  • b92c0ce Update basic-tutorial.md (#402)
  • 4bbe51b Add usage guide section on async logic and data fetching (#401)
  • 92b32db Add code of conduct and contributing files (#395)
  • 69758eb Try adding the compressed-size-action (#372)
  • 717658b Update Docusaurus and add lockfile to 43 version (#369)
  • 4296e74 Update DS to fix sidebar bug
  • 63130ca Remove accidental yarn.lock
  • 762f161 strongly type slice name (#354)
  • 9842933 Update Docusaurus and add lockfile

Compare


Note: You are seeing this because you or someone else with access to this repository has authorized Snyk to open upgrade PRs.

For more information:

🧐 View latest project report

🛠 Adjust upgrade PR settings

🔕 Ignore this dependency or unsubscribe from future upgrade PRs

@emyann emyann merged commit ca033c3 into master Apr 18, 2020
@emyann emyann deleted the snyk-upgrade-7879e597b6c000b3d6ea88df27879214 branch April 18, 2020 00:43
@emyann
Copy link
Owner

emyann commented Apr 18, 2020

🎉 This PR is included in version 1.0.4 🎉

The release is available on:

Your semantic-release bot 📦🚀

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants