@Xaks
Junior Frontend Developer

Где в коде ошибка, что не выводиться counter в консоль?

function createStore(reducer) {
	let state = initialState;
	let callbacks = [];
  
	return {
	  getState() {
		return state;
	  },
	  subscribe(propType, callback) {
		callbacks.push(callback);
	  },
	  unsubscribe(fn) {
		console.log("Unsubscription");
	  },
	  dispatch(action) {
		state = reducer(state, action);
		callbacks.forEach((callback) => callback());
	  }
	};
  }
  
  const initialState = {
	counter: 0
  };
  
  const reducer = (state = initialState, action) => {
	switch (action.type) {
	  case "INCREMENT": {
		return {
		  ...state,
		  counter: state.counter + 1
		};
	  }
	  default:
		return state;
	}
  };
  
  const store = createStore(reducer);
  
  const fn = (counter) => console.log("Counter has been changed", counter);
  
  store.subscribe("counter", fn);
  
  setInterval(() => store.dispatch({ type: "INCREMENT" }), 1000);
  setTimeout(() => store.unsubscribe(fn), 3111);
  • Вопрос задан
  • 108 просмотров
Решения вопроса 1
@User70
На самом деле в коде было 2 ошибки и функция unsubscribe была не реализована.

const initialState = {
    counter: 0
};

function createStore(reducer) {
    let state = initialState;
    let callbacks = [];

    return {
        getState() {
            return state;
        },
        subscribe(propType, callback) {
            callbacks.push(callback);
        },
        unsubscribe(fn) {
            const index = callbacks.indexOf(fn);
            if (index !== -1) {
                callbacks.splice(index, 1);
                console.log("Unsubscription");
            } else {
                throw new Error('Unsubscription error, callback function not found in store.')
            }
        },
        dispatch(action) {
            state = reducer(state, action);
            callbacks.forEach((callback) => callback(state));
        }
    };
}

const reducer = (state = initialState, action) => {
    switch (action.type) {
        case "INCREMENT": {
            return {
                ...state,
                counter: state.counter + 1
            };
        }
        default:
            return state;
    }
};

const store = createStore(reducer);

const fn = (state) => console.log("Counter has been changed", state.counter);

store.subscribe("counter", fn);

setInterval(() => store.dispatch({ type: "INCREMENT" }), 1000);
setTimeout(() => store.unsubscribe(fn), 3111);
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Похожие вопросы