DEV Community

Naveen Dinushka
Naveen Dinushka

Posted on

Handling an action in redux store (Freecodecamp notes)

Notes in QnA format

1. How do we usually handle an action in redux?
We do it by using a function called the Reducer function
2. What does a reducer do?
It takes state, and action as arguments, and it always returns a new state. Reducer doesnt create any side effects, it is simply a pure function that takes state and action , then returns a new state
3.What are some important things to note about reducer?
A key principle in in Redux is that state is read-only, the reducer function must always return a new copy of state and never modify state directly. Redux does not enforce state immutability, however you are responsible for enforcing it in the code of your reducer functions.

4. Below is an example with an example of a reducer function, fill in the body of the reducer function , so that it receives an action of type 'LOGIN' then returns a state object with login set to true, Otherwise it returns current state.?

const defaultState = {
  login: false
};
const reducer = (state = defaultState, action) => {
  // Change code below this line

  // Change code above this line
};
const store = Redux.createStore(reducer);
const loginAction = () => {
  return {
    type: 'LOGIN'

  }
};
Enter fullscreen mode Exit fullscreen mode

Answer

const defaultState = {
  login: false
};

const reducer = (state = defaultState, action) => {
  // Change code below this line
   if(action.type=='LOGIN')
   {
     return {
      login:true
     };
   }
   else{
     return state;
   }
  // Change code above this line
};

const store = Redux.createStore(reducer);

const loginAction = () => {
  return {
    type: 'LOGIN'
  }
};

Enter fullscreen mode Exit fullscreen mode

Knowledge Check

  1. How do we usually handle an action in redux?
  2. What does a reducer do? 3.What are some important things to note about reducer?
  3. Below is an example with an example of a reducer function, fill in the body of the reducer function , so that it receives an action of type 'LOGIN' then returns a state object with login set to true, Otherwise it returns current state.?
const defaultState = {
  login: false
};
const reducer = (state = defaultState, action) => {
  // Change code below this line

  // Change code above this line
};
const store = Redux.createStore(reducer);
const loginAction = () => {
  return {
    type: 'LOGIN'

  }
};
Enter fullscreen mode Exit fullscreen mode

Top comments (0)