0

I want to know what does ...state inside { ...state } do? Is it to change the value of the store to the initial value or to let the store be the latest value?

import * as actionType from "../actions/actionTypes";

const initialStore = {
  roomsCount: 0,
  resPerPage: 0,
  rooms: [],
  filteredRooms: 0,
  error: null,
  success: false,
};

const reducer = (state = initialStore, action) => {
  switch (action.type) {
    case actionType.ALL_ROOM_SUCCESS:
      return {
        ...state,
        success: true,
        rooms: action.rooms,
        roomsCount: action.roomsCount,
        resPerPage: action.resPerPage,
        filteredRooms: action.filteredRooms,
      };
    case actionType.ALL_ROOM_FAILED:
      return {
        ...state,
        error: action.err,
      };
  }
};

If at first I use this reducer, it'll be successful so success will be true and error will be null. But if it fails the 2nd time and I use ...state in this situation, what is the success value? Is it the initial value (false) or does it keep the value from the first request (true)?

Kelvin Schoofs
  • 8,323
  • 1
  • 12
  • 31
Rawand122
  • 327
  • 1
  • 5
  • 12

1 Answers1

0

That is called the spread operator and it basically allows you to "clone" the fields of one object into a new object.

In your example, { ...state, error: action.err } means "copy all fields from state, but set the field error to action.err". It's very handy for this kind of logic where you want to change a very few fields but otherwise want to keep the original data.

Kelvin Schoofs
  • 8,323
  • 1
  • 12
  • 31