J
J
JavaSscriptNoob2022-01-08 13:13:10
JavaScript
JavaSscriptNoob, 2022-01-08 13:13:10

Why is redraw not happening in self-written react-redux?

Hello everyone, this is how I change my state:
store itself:

const initialState = { firstname: "" };
const reducer = (state = initialState, action) => {
  switch (action.type) {
    case "SET_FIRSTNAME":
      state.firstname = action.payload.firstname;
      return {
        ...state,
      };
    default:
      return state;
  }
};

export const createStore = (reducer) => {
  let state = reducer(undefined, {});
  let callback;
  return {
    dispatch: (action) => {
      reducer(state, action);
      callback();
    },
    getState: () => state,
    subscribe: (cb) => {
      callback = cb;
    },
  };
};
export const store = createStore(reducer);

How change happens
store.subscribe(() => {
      setUser(store.getState());
    });

However, if the change is
store.subscribe(() => {
      setUser({ ... store.getState()});
    });

then everything works ...
I don’t throw off actions, etc., since they are 100% correct.
setUser- f-i for change useState(due to what the change occurs)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Belyaev, 2022-01-08
@JavaSscriptNoob

state.firstname = action.payload.firstname;here you are mutating the previous state, potentially making it impossible to compare states.
reducer(state, action);the returned state is not written anywhere.
callback();But here there can be a potential error, since the callback can be undefined

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question