@jsasz/jreducer
TypeScript icon, indicating that this package has built-in type declarations

0.0.9 • Public • Published

The reducer

Create the reducer and action creator combination

export const [playerReducer, updatePlayer] = createReducer({
  citiesConquered: [],
  name: "The game hero",
  points: 0,
});

Use the action creator to create more unique actions

export const playerIncrementPoints = (points) =>
  updatePlayer(player => ({
    ...player,
    points: player.points + points
  }));

export const playerOwnCity = (city) =>
  updatePlayer(player => {
    if (player.cities.some(c => city.key === c.key))
      throw new Error("Player already conquered that city");
    return {
      ...player,
      citiesConquered: player.cities.concat(city)
    };
  });

And then we can put them inside of our redux store

export const [playerReducer, _updatePlayer] = createReducer<Player>({
  cities: [],
  name: "player",
  points: 0
});

export const [citiesReducer, _updateCity] = createRecordReducer({
  [0]: { key: 0 }
});

const reducer = combineReducers({
  player: playerReducer,
  cities: citiesReducer
});

Variations

Record reducer

const updateCityPopulation = (key, amount) =>
  updateCity(key, city => ({
    ...city,
    population: city.population + amount
  }))

Array reducer

const updateCityPopulation = (index, amount) =>
  updateCity(index, city => ({
    ...city,
    population: city.population + amount
  }))

Connect with react-redux

export const App = connect(
  (state) => state,
  {
    updateCityPopulation,
    playerOwnCity,
    playerIncrementPoints,
  }
)((props) => {
  // ... props.updateCityPopulation ... props.playerOwnCity ... props.playerIncrementPoints
  return (
    // ... props.state
  );
});

Readme

Keywords

none

Package Sidebar

Install

npm i @jsasz/jreducer

Weekly Downloads

0

Version

0.0.9

License

MIT

Unpacked Size

12 kB

Total Files

6

Last publish

Collaborators

  • jsasz