Code Monkey home page Code Monkey logo

autodux's Introduction

Autodux

Coverage Status

Redux on autopilot.

Brought to you by EricElliottJS.com and DevAnywhere.io.

Install

npm install --save autodux

And then in your file:

import autodux from 'autodux';

Or using CommonJS syntax:

const autodux = require('autodux');

Redux on Autopilot

Autodux lets you create reducers like this:

export const {
  actions: {
    setUser, setUserName, setAvatar
  },
  selectors: {
    getUser, getUserName, getAvatar
  }
} = autodux({
  slice: 'user',
  initial: {
    userName: 'Anonymous',
    avatar: 'anon.png'
  }
});

That creates a full set of action creators, selectors, reducers, and action type constants -- everything you need for fully functional Redux state management.

Everything's on autopilot -- but you can override everything when you need to.

Why

Redux is great, but you have to make a lot of boilerplate:

  • Action type constants
  • Action creators
  • Reducers
  • Selectors

It's great that Redux is such a low-level tool. It's allowed a lot of flexibility and enabled the community to experiment with best practices and patterns.

It's terrible that Redux is such a low-level tool. It turns out that:

  • Most reducers spend most of their logic switching over action types.
  • Most of the actual state updates could be replaced with generic tools like "concat payload to an array", "remove object from array by some prop", or "increment a number". Better to reuse utilities than to implement these things from scratch every time.
  • Lots of action creators don't need arguments or payloads -- just action types.
  • Action types can be automatically generated by combining the name of the state slice with the name of the action, e.g., counter/increment.
  • Lots of selectors just need to grab the state slice.

Lots of Redux beginners separate all these things into separate files, meaning you have to open and import a whole bunch of files just to get some simple state management in your app.

What if you could write some simple, declarative code that would automatically create your:

  • Action type constants
  • Reducer switching logic
  • State slice selectors
  • Action object shape - automatically inserting the correct action type so all you have to worry about is the payload
  • Action creators if the input is the payload or no payload is required, i.e., x => ({ type: 'foo', payload: x })
  • Action reducers if the state can be assigned from the action payload (i.e., {...state, ...payload})

Turns out, when you add this simple logic on top of Redux, you can do a lot more with a lot less code.

import autodux, { id } from 'autodux';

export const {
  reducer,
  initial,
  slice,
  actions: {
    increment,
    decrement,
    multiply
  },
  selectors: {
    getValue
  }
} = autodux({
  // the slice of state your reducer controls
  slice: 'counter',

  // The initial value of your reducer state
  initial: 0,

  // No need to implement switching logic -- it's
  // done for you.
  actions: {
    increment: state => state + 1,
    decrement: state => state - 1,
    multiply: (state, payload) => state * payload
  },

  // No need to select the state slice -- it's done for you.
  selectors: {
    getValue: id
  }
});

As you can see, you can destructure and export the return value directly where you call autodux() to reduce boilerplate to a minimum. It returns an object that looks like this:

{
  initial: 0,
  actions: {
    increment: { [Function]
      type: 'counter/increment'
    },
    decrement: { [Function]
      type: 'counter/decrement'
    },
    multiply: { [Function]
      type: 'counter/multiply'
    }
  },
  selectors: {
    getValue: [Function: wrapper]
  },
  reducer: [Function: reducer],
  slice: 'counter'
}

Let's explore that object a bit:

const actions = [
  increment(),
  increment(),
  increment(),
  decrement()
];

const state = actions.reduce(reducer, initial);

console.log(getValue({ counter: state })); // 2
console.log(increment.type); // 'counter/increment'

API Differences

Action creators, reducers and selectors have simplified APIs.

Automate (Almost) Everything with Defaults

With autodux, you can omit (almost) everything.

Default Actions

An action is an action creator/reducer pair. Usually, these line up in neat 1:1 mappings. It turns out, you can do a lot with some simple defaults:

  • A set${slice} action lets you set any key in your reducer -- basically: {...state, ...payload}. If your slice is called user, the set creator will be called setUser.
  • Actions for set{key} will exist for each key in your initial state. If you have a key called userName, you'll have an action called setUserName created automatically.

Default Selectors

Like action creators and reducers, selectors are automatically created for each key in your initial state. get{key} will exist for each key in your initial state., and get{slice} will exist for the entire reducer state.

For simple reducers, all the action creators, reducers, and selectors can be created for you automatically. All you have to do is specify the initial state shape and export the bindings.

Action Creators

Action creators are optional! If you need to set a username, you might normally create an action creator like this:

const setUserName = userName => ({
  type: 'userReducer/setUserName',
  payload: userName
})

With autodux, if your action creator maps directly from input to payload, you can omit it. autodux will do it for you.

By omitting the action creator, you can shorten this:

actions: {
  multiply: {
    create: by => by,
    reducer: (state, payload) => state * payload
  }
}

To this:

actions: {
  multiply: (state, payload) => state * payload
}

No need to set the type

You don't need to worry about setting the type in autodux action creators. That's handled for you automatically. In other words, all an action creator has to do is return the payload.

With Redux alone you might write:

const setUserName = userName => ({
  type: 'userReducer/setUserName',
  payload: userName
})

With autodux, that becomes:

userName => userName

Since that's the default behavior, you can omit that one entirely.

You don't need to create action creators unless you need to map the inputs to a different payload output. For example, if you need to translate between an auth provider user and your own application user objects, you could use an action creator like this:

({ userId, displayName }) => ({ uid: userId, userName: displayName })

Here's how you'd implement our multiply action if you want to use a named parameter for the multiplication factor:

//...
actions: {
  multiply: {
    // Destructure the named parameter, and return it
    // as the action payload:
    create: ({ by }) => by,
    reducer: (state, payload) => state * payload
  }
}
//...

Reducers

Note: Reducers are optional. If your reducer would just assign the payload props to the state ({...state, ...payload}), you're already done.

No switch required

Switching over different action types is automatic, so we don't need an action object that isolates the action type and payload. Instead, we pass the action payload directly, e.g:

With Redux:

const INCREMENT = 'INCREMENT';
const DECREMENT = 'DECREMENT';
const MULTIPLY = 'MULTIPLY';

const counter = (state = 0, action = {}) {
  switch (action.type){
    case INCREMENT: return state + 1;
    case DECREMENT: return state - 1;
    case MULTIPLY : return state * action.payload
    default: return state;
  }
};

With Autodux, action type handlers are switched over automatically. No more switching logic or manual juggling with action type constants.

const counter = autodux({
  slice: 'counter',
  initial: 0,
  actions: {
    increment: state => state + 1,
    decrement: state => state - 1,
    multiply: (state, payload) => state * payload
  }
});

Autodux infers action types for you automatically using the slice and the action name, and eliminates the need to write switching logic or worry about (or forget) the default case.

Because the switching is handled automatically, your reducers don't need to worry about the action type. Instead, they're passed the payload directly.

Selectors

Note: Selectors are optional. By default, every key in your initial state will have its own selector, prepended with get and camelCased. For example, if you have a key called userName, a getUserName selector will be created automatically.

Selectors are designed to take the application's complete root state object, but the slice you care about is automatically selected for you, so you can write your selectors as if you're only dealing with the local reducer.

This has some implications with unit tests. The following selector will just return the local reducer state (Note: You'll automatically get a default selector that does the same thing, so you don't ever need to do this yourself):

import { autodux, id } from 'autodux';

const counter = autodux({
  // stuff here
  selectors: {
    getValue: id // state => state
  },
  // other stuff

In your unit tests, you'll need to pass the key for the state slice to mock the global store state:

test('counter.getValue', assert => {
  const msg = 'should return the current count';
  const { getValue } = counter.selectors;

  const actual = getValue({ counter: 3 });
  const expected = 3;

  assert.same(actual, expected, msg);
  assert.end();
});

Although you should avoid selecting state from outside the slice you care about, the root state object is passed as a convenience second argument to selectors:

import autodux from 'autodux';

const counter = autodux({
  // stuff here
  selectors: {
    // other selectors
    rootState: (_, root) => root
  },
  // other stuff

In your unit tests, this allows you to retrieve the entire root state:

test('counter.rootState', assert => {
  const msg = 'should return the root state';
  const { rootState } = counter.selectors;

  const actual = rootState({ counter: 3, otherSlice: 'data' });
  const expected = { counter: 3, otherSlice: 'data' };

  assert.same(actual, expected, msg);
  assert.end();
});

Extras

assign = (key: String) => reducer: Function

Often, we want our reducers to simply set a key in the state to the payload value. assign() makes that easy. e.g.:

const {
  actions: {
    setUserName,
    setAvatar
  },
  reducer
} = autodux({
  slice: 'user',
  initial: {
    userName: 'Anonymous',
    avatar: 'anonymous.png'
  },
  actions: {
    setUserName: assign('userName'),
    setAvatar: assign('avatar')
  }
});

const userName = 'Foo';
const avatar = 'foo.png';

const state = [
  setUserName(userName),
  setAvatar(avatar)
].reduce(reducer, undefined);
// => { userName: 'Foo', avatar: 'foo.png' }

Since that's the default behavior when actions are omitted, you can also shorten that to:

const {
  actions: {
    setUserName,
    setAvatar
  },
  reducer
} = autodux({
  slice: 'user',
  initial: {
    userName: 'Anonymous',
    avatar: 'anonymous.png'
  }
});

id = x => x

Useful for selectors that simply return the slice state:

selectors: {
  getValue: id
}

autodux's People

Contributors

alvaropinot avatar dependabot[bot] avatar ellaylone avatar emiphil avatar ericelliott avatar grushetsky avatar kennylavender avatar meszaros-lajos-gyorgy avatar nuba avatar renovate-bot avatar ryanbas21 avatar warrenv avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

autodux's Issues

Proposal: Autoprov

Motivation

Ever since hooks and the context API released, I like to use useContext() for my global state similar to this:

// state.js
import React, {createContext, useContext, useState} from 'react';

const StateContext = createContext();

export const StateProvider = ({initialState, children}) =>(
  <StateContext.Provider value={useState(initialState)}>
    {children}
  </StateContext.Provider>
);

export const useStateValue = () => useContext(StateContext);

// App.js
import { StateProvider } from '../state';

const App = () => {
  const initialState = 1;
  
  return (
    <StateProvider initialState={initialState}>
        // App content ...
    </StateProvider>
  );
}

// Counter.js
import { useStateValue } from './state';

const Counter = () => {
  const [counter, setCount] = useStateValue();
  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

While this example is written with useState, in reality I mostly use reducers. I typically generate these using Autodux. But using this global state pattern with useReducer also comes with a lot of boilerplate.

Solution / Proposal

Either as an addition to this package, or as a stand alone, we could write autoprov.

Here is how the API would be used:

state.js:

import { autoprov } from "autodux";

import {
  actions as counterActions,
  reducer as counter,
  getCounter
} from "./counter-reducer";
import {
  actions as toggleActions,
  reducer as toggle,
  getToggle
} from "./toggle-reducer";
import {
  actions as textActions,
  reducer as text,
  getText
} from "./text-reducer";

const { StateProvider, useBuildSlice } = autoprov({ counter, toggle, text });

const useCounter = () => {
  return useBuildSlice({
    selector: getCounter,
    alias: "clicks",
    actions: counterActions
  });
};

const useToggle = () => {
  return useBuildSlice({
    selector: getToggle,
    alias: "on",
    actions: toggleActions
  });
};

const useText = () => {
  return useBuildSlice({
    selector: getText,
    alias: "text",
    actions: textActions
  });
};

export { StateProvider, useCounter, useToggle, useText };

App.js:

import React, { Fragment } from "react";
import ReactDOM from "react-dom";

import "./styles.css";
import { useCounter, StateProvider, useToggle, useText } from "./state";

function Global() {
  const { text } = useText();
  const { clicks } = useCounter();
  return (
    <div>
      <div>Global Clicks: {clicks}</div>
      <div>Global Text: {text}</div>
    </div>
  );
}

const Counter = ({ clicks, onDecrement, onIncrement }) => (
  <Fragment>
    Clicks: <span className="clicks-count">{clicks}</span>&nbsp;
    <button className="click-dec-button" onClick={onDecrement}>
      Minus
    </button>
    <button className="click-inc-button" onClick={onIncrement}>
      Plus
    </button>
  </Fragment>
);

const Toggle = ({ on, onToggle }) => (
  <Fragment>
    The Switch is: <span className="toggle-state">{on ? "on" : "off"}</span>
    {on}&nbsp;
    <button className="toggle-button" onClick={onToggle}>
      Toggle
    </button>
  </Fragment>
);

function App() {
  const { clicks, decrement, increment } = useCounter();
  const { on, toggle } = useToggle();
  const { text, setText } = useText();
  return (
    <div className="App">
      <Counter
        clicks={clicks}
        onDecrement={decrement}
        onIncrement={increment}
      />
      <br />
      <Toggle on={on} onToggle={toggle} />
      <br />
      <input value={text} onChange={e => setText(e.target.value)} />
      <Global />
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(
  <StateProvider>
    <App />
  </StateProvider>,
  rootElement
);

Here is a CodeSandBox with a whacky implementation.

What do you think? This would make it easy to use global state with context. I also like the functional composition nature of just being able to use useText() in a component. Obviously the name useBuildSlice should be changed ๐Ÿ˜„

How to properly combine\nest autodux?

Hello! I've started to use autodux for a while, it's really convenient, but I'm facing a problem with nesting for autodux generated entities. Let's say I want to nest some sub features into feature:

import { combineReducers } from 'redux';
import { reducer as requests } from './features/requests';

// This is my 'manage' feature
export const reducer = combineReducers({
  requests,
});

Here is autodux for 'requests':

export const { actions, reducer, selectors, slice } = autodux({
  actions: {
    ...fetchActions,
  },
  initial: initialState,
  slice: 'requests', // For me this should sound like 'manage/requests'
});

If i combine reducers this way, generated selectors is looking for slice state['requests'], but actually slice in state.manage.requests . Also action types have namespace requests/myAction, but i want it to be manage/requests/myAction. Is there an autodux way for this kind of using? Or am I missing something in redux basics? I will be grateful for any help. Thanks!

Create an action creator for clearing the reducer

I often find myself writing a clear action creator:

import autodux from 'autodux';

const initial = '';

export const {
  reducer: name,
  actions: { setName, clearName },
  selectors: { getName },
} = autodux({
  slice: 'name',
  initial,
  actions: {
    clearName: () => initial,
  },
});

I'm interested in creating a PR to add this clear action creator for the slice and each key of the initial object (similar to the set action creator). Would you be open for that?

Autodux doesn't work in CodeSandBox

I wanted to recreate the component of Eric's article in codesandbox: https://codesandbox.io/s/m9v130182j

But autodux can't be compiled by CodeSandbox and throws:

TypeError
Cannot read property 'package' of undefined

Here is the code:

import React, { Fragment, useReducer } from "react";
import ReactDOM from "react-dom";
import autodux from "autodux";

import "./styles.css";

const {
  reducer,
  actions: { click }
} = autodux({
  slice: "counter",
  initial: 0,
  actions: {
    click: count => count + 1
  }
});

const Counter = ({ clicks, onClick }) => (
  <Fragment>
    Clicks: <span className="clicks-count">{clicks}</span>&nbsp;
    <button className="click-button" onClick={onClick}>
      Click
    </button>
  </Fragment>
);

function App() {
  const [clicks, dispatch] = useReducer(reducer, reducer());
  return (
    <div className="App">
      <Counter clicks={clicks} onClick={() => dispatch(click())} />;
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Is there a dist/cdn version of autodux?

I'm importing autodux into a project, which uses rollupjs to bundle my component but it's adding all of rambdajs, so it takes a 5kb and turns it into 66kb file.

I might have to figure out how to make adjustments to my rollupjs configuration, if there was a dist of this I guess I could treat it as an external dependency.

Async actions?

Love the concept of autodux! Do you have any plans to add support for async/await style actions? I'm thinking fetching data from an API etc... :)

Updated version

  • Reproduce features
  • Work with React useState out of the box
  • d.ts first
  • Use mutative
  • async effects
  • Compare with Zustand in docs. Why Autodux instead of Zustand?

References:

  • Zustand stand-alone + Redux support

5.0.1 is pointing to src instead of dist

Hi.

Autodux is breaking my application on IE11 because on latest version the module use /src instead of /dist.

If i downgrade to 5.0, autodux prevent me to build because of an error "Can't resolve './errors'".

I opened a PR, it should be enough to fix the issue : #94

Webpack breaks with ES6

Hi @ericelliott,

Thanks for autodux, it's really nice and useful! :)

I know this is still in "developer preview mode", so what folows is more of a suggestion than a bug report.

Please consider releasing as ES5 too.

In a new project with @angular/cli: 1.2.6 the build breaks with

ERROR in vendor.42b3b802a29f068797b9.bundle.js from UglifyJs
Invalid assignment [/home/nuba/IdeaProjects/understudio-angular-quickstart/~/autodux/source/index.js:3,0][vendor.42b3b802a29f068797b9.bundle.js:20545,47]

And with @angular/cli we're quite limited when it comes to tweaking webpack's behaviour to add a preprocessor or something.

I worked around it by embedding autodux (as it's really small) in my ts code (which then had ES5 as target in tsconfig.json). But just calling tsc --allowJs -t ES5 index.js --outFile index.ES5.js did the trick ;)

Thanks, keep rocking!

Nuba

Selectors in nested reducer

My state look like this : { entities : { user : { ... } }, login : { ... } ... }
I have a dedicated reducer for my 'user' entity. Therefore, its selectors are not working : they are expecting to find user at the top level of my state, so the first parameter that my selectors receive is undefined.

Am i doing something wrong, or autodux can't generate me working selectors in that case ?

This issue is related to #29, but my state shape is pretty common and i find disturbing that its not supported, i dont want to design my state around autodux limitations.

If its the second option, a potential workaround would be to be able to define slices like 'entities.user'. What do you think ?

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Rate-Limited

These updates are currently rate-limited. Click on a checkbox below to force their creation now.

  • Update dependency eslint-config-prettier to v9
  • Update dependency eslint-plugin-prettier to v5
  • Update dependency husky to v9
  • Update dependency lint-staged to v15
  • Update dependency prettier to v3
  • Update dependency riteway to v7
  • Update dependency textlint to v14
  • Update dependency textlint-rule-terminology to v5
  • Update dependency updtr to v4
  • ๐Ÿ” Create all rate-limited PRs at once ๐Ÿ”

Edited/Blocked

These updates have been manually edited so Renovate will no longer make changes. To discard all commits and start over, click on a checkbox.

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Detected dependencies

npm
package.json
  • esm 3.2.25
  • ramda 0.27.1
  • @textlint-rule/textlint-rule-no-invalid-control-character 1.2.0
  • coveralls 3.1.0
  • eslint 6.8.0
  • eslint-config-prettier 6.10.0
  • eslint-plugin-prettier 3.1.4
  • husky 3.1.0
  • lint-staged 9.5.0
  • markdownlint-cli 0.23.2
  • nyc 14.1.1
  • prettier 1.19.1
  • riteway 6.2.0
  • tap-nirvana 1.1.0
  • textlint 11.7.6
  • textlint-rule-common-misspellings 1.0.1
  • textlint-rule-terminology 1.1.30
  • updtr 3.1.0
  • watch 1.0.2
travis
.travis.yml
  • node 10

  • Check this box to trigger a request for Renovate to run again on this repository

Add autodux combineReducers version

This code does not look very good

const rootReducer = combineReducers({
  orders: orders.reducer,
  ordersTable: ordersTable.reducer,
  selectedOrderIds: selectedOrderIds.reducer,
  map: map.reducer,
  now: map.reducer,
});

I suggest adding a custom autodux combineReducers:

import { combineReducers } from 'autodux';

const rootReducer = combineReducers({
  orders,
  ordersTable,
  selectedOrderIds,
  map,
  now,
});

The module `./errors` could not be found

Using Autodux with a React Native app created by Expo and Yarn throws:

Unable to resolve module `./errors` from `/Users/jan/Startup/react-native/os-gastro-admin/node_modules/autodux/dist/index.js`: The module `./errors` could not be found from `/Users/jan/Startup/react-native/os-gastro-admin/node_modules/autodux/dist/index.js`. Indeed, none of these files exist:
  * `/Users/jan/Startup/react-native/os-gastro-admin/node_modules/autodux/dist/errors(.native||.ios.js|.native.js|.js|.ios.json|.native.json|.json|.ios.ts|.native.ts|.ts|.ios.tsx|.native.tsx|.tsx)`
  * `/Users/jan/Startup/react-native/os-gastro-admin/node_modules/autodux/dist/errors/index(.native||.ios.js|.native.js|.js|.ios.json|.native.json|.json|.ios.ts|.native.ts|.ts|.ios.tsx|.native.tsx|.tsx)`

ABI32_0_0RCTFatal
__37-[ABI32_0_0RCTCxxBridge handleError:]_block_invoke
_dispatch_call_block_and_release
_dispatch_client_callout
_dispatch_main_queue_callback_4CF
__CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__
__CFRunLoopRun
CFRunLoopRunSpecific
GSEventRunModal
UIApplicationMain
main
start

Somehow it loads from dist instead of source. Inspecting node_modules shows that dist is lacking the errors.js file.

Steps to reproduce:

  1. Create a new app using expo init
  2. Add autodux using yarn add autodux
  3. Add redux and react-redux and connect it to a reducer created with autodux

You can fix the issue by copying errors.js from src to dist.

What's the best practice for creating actions that do not transform state?

I'm not sure why I'm having a hard time with this but, I'm struggling to find a way to create an action that Saga can listen to, without autodux having to update the state. Without trying to create an action outside of my autodux.

For example, if I'm creating a "REQUEST" action, without it setting any state, that my saga can listen to, but autodux isn't expecting to change the state. I want my saga to dispatch, and then update state based on request-response.

Is this the solution?

actions: { startMarkRead: (state) => state, }

Default action creators payload

Hi, I'm trying out autodux default action creators, and while writing tests noticed that instead of getting action like this one:

{
    type: 'user/setUser',
    payload: {
        userName: 'Foo',
        avatar: 'foo.png'
    }
 }

I'm getting copy of an action inside payload, like this:

{
    type: 'user/setUser',
    payload: {
        type: 'user/setUser',
        payload: {
            userName: 'Foo',
            avatar: 'foo.png'
        }
     }
 }

Sample test:

const {
    actions: {
        setUser
    },
    reducer
} = autodux({
    slice: 'user',
    initial: {
        userName: 'Anonymous',
        avatar: 'anonymous.png'
    }
});
const userName = 'Foo';
const avatar = 'foo.png';

const actual = setUser({ userName, avatar });
const expected = {
    type: 'user/setUser',
    payload: {
        userName,
        avatar,
    }
};

What am I doing wrong and how can I fix it so that default action creators form correct action?

Implicit core-js dependency ?

When trying to test autodux, i meet a missing dependency error.
I see that there is a lot of import from core-js like this :
import 'core-js/modules/es6.array.reduce-right';
but i see no mention of core-js in the package.json.
Is there something i'm missing ?
Should those imports be somewhat removed by babel if not needed ? Is my babel config wrong ?
Thank you.

TypeScript support?

Hi,

do you plan to export some TypeScript/Flow definitions for the library?

Payload returning undefined

After doing a bit of testing, I'm still finding that the payload is returning undefined with the actions being generated. The action type is pulling through but payload is not. I recreated the multiply function in the README.md and the payload is still returning undefined in that instance.

Here is an example of the autodux object.

const tweetsSlice = autodux({
  slice: 'tweets',
  initial: defaultState,
  actions: {
    multiply: {
      reducer: (state, payload) => state.num * payload
    },
    submit: {
      reducer: (state, payload) =>  `state: ${state} payload: ${payload}`
    }
  },
  selectors: {
    getValue: id,
  }
});

Payload is returning undefined the the following tests:

test('submit()', assert => {
  const msg = 'should have an action type and a payload.';
  const payload = {
    id: '12344',
    text: 'some text'
  };
  const actual = submit(payload);
  const expected = { type: submit().type, payload};  
  
  assert.same(actual, expected, msg);
  assert.end();
});
test('multiply', assert => {
  const msg = 'should multiply the state by the payload.';

  const payload = 3;
  const actual = multiply(payload);
  const expected = 3; // 3 * 1
  
  assert.same(actual, expected, msg);
  assert.end();
});

Debug actions

I cannot debugger or console.log inside an action. It does nothing and also swallows all errors.

How can I see what is going on inside an action?

export const {
  reducer: platformReducer,
  actions: platformActions
} = autodux({
  slice: 'platforms',
  initial: {},
  actions: {
    setPlatforms: (_, payload) => {
      const newPlatform = {};
      console.log(payload);
      debugger;
      payload.forEach(g => newPlatforms[g.id] = g);
      return newPlatforms;
    }
  }
});

Return the slice property

Return the slice property so that it can be exported for selector tests.

const {
  slice, // destructure the slice property for export
  selectors: { getValue },
  actions: {
    increment,
    decrement
  },
  reducer,
  initial
} = autodux({
  slice: 'counter',
  initial: 0,
  ...
});

How can I have my reducer react to a common action?

Let's say I have an action called clear that should reset reducers to their initialState (e.g. after user logs out). Before autodux I would do it like this (Example is in TypeScipt, which our team abandoned after reading your TypeScript Tax article, which was aligned with our experiences):

export const byId = (state = initialState, action: RestaurantAction) => {
  switch (action.type) {
    case getType(restaurants.add):
      return { ...state, ...action.payload };
    case getType(restaurants.addMenus):
      return {
        ...state,
        [action.payload.restaurantSlug]: {
          ...state[action.payload.restaurantSlug],
          menus: action.payload.menus
        }
      };
    case getType(generics.clear):
      return initialState;
    default:
      return state;
  }
};

const initialLoadingState: boolean = false;

export const loaded = (state = initialLoadingState, action: RestaurantAction) => {
  switch (action.type) {
    case getType(restaurants.loading):
      return false;
    case getType(restaurants.loaded):
      return true;
    case getType(generics.clear):
      return initialLoadingState;
    default:
      return state;
  }
};

How would one do that with autodux? Can you have reducers react to a common action? Or would I have to write a clear action for each reducer like this:

import autodux from 'autodux';

const initial = {};

export const {
	reducer: byId,
	actions: { setRestaurants, clear },
	selectors,
} = autodux({
	slice: 'restaurants',
	initial,
	actions: { clear: () => initial },
});

import them all in one file and write a wrapper that batch dispatches all clear functions?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.