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
);
});