D
D
dikyzz2019-10-25 09:57:00
React
dikyzz, 2019-10-25 09:57:00

Next.js + Redux does not update state. Where is the mistake?

Essence such:
1. On page in getInitialProps I call the asynchronous function receiving statistics of the user.

class Statistics extends React.Component<StatisticsProps> {
  static async getInitialProps({ req, res }: NextPageContext) {
    const token = getCookie('authtoken', req);
    if (!token) {
      redirect('/auth', res);
      return false;
    }

store.dispatch(requestUserStatistics());
    StatisticsService.getUserStatistics();
  }
// Остальной код страницы

2. I don’t expect an answer, because inside the function there is an action call, which, as planned, should update the global state, the data of which will be displayed in the necessary components upon appearance
export default class StatisticsService {
  static async getUserStatistics(params?: Readonly<{ [key: string]: any }>) {
    const res = await post<StatisticsResponse>(`/api/economics/lk/stat/`, params);

    if(!res.data.error) {
      // console.log("disp disp disp", res.data)
      store.dispatch(receiveUserStatistics({result: res.data.result, result_total: res.data.result_total, chartFields: ["users", "visits"]}));
    }

    return res.data;
  }
}

3. Inside the reducer, which is generally the last step before updating the state, I see that the data is coming and ready to be written
case RECEIVE_USER_STATISTICS:
      console.log("received", action.statistics)
      return {
        ...state,
        statistics: action.statistics,
        isLoadingStatistics: false
      };

4. For some reason, the state update does not occur. And if you check the state itself, then there is no information there. At the same time, if we go to the same page from another one (that is, the render will not be on the server, but on the client), then the data is loaded and everything works.
If you take out the call of all this persimmon from getInitialProps to componentDidMount, then the data also appears on the page in a second (as long as the request goes).
componentDidMount() {
    store.dispatch(requestUserStatistics());
    StatisticsService.getUserStatistics();
  }

Those. in the first case it doesn't work, but in the second it works. Why is that?
There is an idea that this is due to server rendering. Could it be that he makes a request to the server, but does not wait for a response and returns the page to the client, in connection with which the object's record in the state is lost?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question