L
L
lookingfor22021-01-11 10:44:18
React
lookingfor2, 2021-01-11 10:44:18

Can i get actual state in js file?

I'm trying to get the current state through getState (), while I know that the state has been changed, and not updated data is returned to me,

that's what's in the store file

export function initializeStore(initialState = baseState) {

  return createStore(
    mainReducer,
    initialState,
    composeWithDevTools(applyMiddleware(thunk))
  );

}

export const baseReducer = (state = baseState, action) => {
  switch (action.type) {

  case TEST: {

    return {...state, isTest: true};

  }
  case UPDATE_TOKEN: {

    return {...state, userAuthToken: action.payload};

  }

  case "SET_PROJECT_DATA": {

    return state = {
      ...state,
      [action.payload.name]: action.payload.value
    };

  }
  case "SET_PROJECT_DATA_ARRAY": {

    action.payload.forEach(function (item) {

      if (typeof item === "object") {

        const keys = Object.keys(item);
        keys.forEach((key) => state = {
          ...state,
          [key]: item[key]
        });

      }

    });

  }

  case "CLEAR_PROJECT_ERRORS": {

    return state = {...state, [action.payload.name]: ""};

  }
  default:
    return state;

  }
};


js file
export const submitStepOne = () => async (dispatch, getState) => {

  const registerData = {
    a: 1
  };

  try {
    const responseA = await a(registerData);
    dispatch(setData("newUser", responseA.data));
  } catch (error) {
    dispatch(setData("error", error));
  }

 // пытаюсь получить стор, возвращает старый
  setTimeout(() => console.log(getState().base), 1000);

  if (!getState().base.projectError) {
    Router.push("/registration/two");
  }


};

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Ukolov, 2021-01-11
@lookingfor2

case "SET_PROJECT_DATA": {
  return state = {
    ...state,
    [action.payload.name]: action.payload.value
  };
}

It is absolutely not necessary to equate to state here (and in other places), you just need to return a new object.
case "SET_PROJECT_DATA_ARRAY": {
  action.payload.forEach(function (item) {
    if (typeof item === "object") {
      const keys = Object.keys(item);
      keys.forEach((key) => state = {
        ...state,
        [key]: item[key]
      });
    }
  });
}
And here you are completely mutating the state object, while not returning anything. You must return a completely new object here, without changing the old one in any way.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question