Write a Counter with Redux
Randy Rivera
Posted on November 30, 2021
- Now that both you and I have learned all the core principles of Redux! We've seen how to create actions and action creators, create a Redux store, dispatch your actions against the store, and design state updates with reducers. You've even seen how to manage complex state with reducer composition and handle asynchronous actions.
In this section, you'll execute a simple counter with Redux from scratch. The basics are provided in the code editor, but you'll have to fill it all in. Once you're finished you should be able to dispatch INCREMENT or DECREMENT actions to increment or decrement the state held in the store. Good luck building your first Redux app.
Provided Code:
const INCREMENT = null; // Define a constant for increment action types
const DECREMENT = null; // Define a constant for decrement action types
const counterReducer = null; // Define the counter reducer which will increment or decrement the state based on the action it receives
const incAction = null; // Define an action creator for incrementing
const decAction = null; // Define an action creator for decrementing
const store = null; // Define the Redux store here, passing in your reducers
- Answer:
const INCREMENT = 'INCREMENT';
const DECREMENT = 'DECREMENT';
const counterReducer = (state = 0, action) => {
switch(action.type) {
case INCREMENT:
return state + 1
case DECREMENT:
return state - 1
default:
return state
}
}
const incAction = () => {
return {
type: INCREMENT
}
};
const decAction = () => {
return {
type: DECREMENT
}
};
const store = Redux.createStore(counterReducer);
console.log(store.getState()) // 0
store.dispatch(incAction())
console.log(store.getState()) // 1
💖 💪 🙅 🚩
Randy Rivera
Posted on November 30, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.