Redux-сага отправка вернуть столько запросов - PullRequest
1 голос
/ 26 февраля 2020

я строю свои сервисы с помощью Ax ios мои редукторы и действия строятся на основе шаблона Duck, но все работает, но мой dispatch() in componentDidMount() посылает так много запросов моему API.

This send almost 3k of calls in 3 minutes!

Я уже пробовал с промежуточным программным обеспечением sagin cancel () с take (), но ничего не работает: /

утки / таблица. js

export const Types = {
  GET_ALL: 'booking/GET_ALL'
};

const initialState = {
  all: null
};

export default function reducer(state = initialState, action) {
  const { type, payload } = action;

  switch (type) {
    case Types.GET_ALL:
      return { 
        ...state,
        all: payload
      };
    default:
      return state;
  }

}

export const fetchAll = data => ({ type: Types.GET_ALL, payload: data });

услуги / таблица. js

import Http from "../utils/http";

export const getAll = async () => {
  try {
    const response = await Http.get('/todos/1');

    if (response.data) {
      return response.data;
    }

    throw response.data;
  } catch (error) {
    throw error;
  }
};

саги / таблица. js

import { put, call } from 'redux-saga/effects';

import { getAll } from '../services/table'
import { fetchAll } from '../ducks/table';

export function* tableCheck(action) {
    try {       

        let data = yield call(getAll);
        yield put(fetchAll(data));

        console.log("tableCheck => try => action", action)      

    } catch (error) {

        //ToDo criar authError
        yield put(error)
    }
}

store / index. js

import { createStore, applyMiddleware } from "redux";
import createSagaMiddleware from "redux-saga";

import reducers from "./reducers";
import rootSaga from "./sagas";

const sagaMiddleware = createSagaMiddleware();

const store = createStore(reducers, applyMiddleware(sagaMiddleware));

sagaMiddleware.run(rootSaga);

export default store;

store / sagas. js

import { takeLatest } from 'redux-saga/effects';

import { tableCheck } from '../sagas/table';

import { Types as bookingTypes } from '../ducks/table';

export default function* rootSaga() {
    yield takeLatest(bookingTypes.GET_ALL, tableCheck)
}

накопитель / редуктор. js

import { combineReducers } from "redux";

import bookings from "../ducks/table";

const appReducer = combineReducers({
  bookings
});
const rootReducer = (state, action) => {
  return appReducer(state, action);
};

export default rootReducer;

компоненты / приложение. js

import React, { Component } from 'react';
import { connect } from 'react-redux';

import Table from "./common/table";
import { fetchAll } from './ducks/table';

class App extends Component {

  constructor(props) {
    super(props);

    this.state = {
      headers: ["#", "Name", "Check In", "Date", "Status"]
    };

    this.handleClick = this.handleClick.bind(this);    
  }

  async componentDidMount() {    
    //console.log("app => componentDidMount() => fetchAll()", await fetchAll())
    console.log("app => componentDidMount() => this.state", await this.state);
    console.log("app => componentDidMount() => this.props", await this.props);
    await this.props.dispatch(fetchAll());

    //<Table headings={this.state.headers} />

  }



  handleClick(e) {
    e.preventDefault();
    console.log("class App => handleClick() => this.props", this.props);
    console.log("class App => handleClick() => this.state", this.state);

  }

  render() {
    return (
      <div>
        <p className="header">React Table Component</p>

        <p>
          Made with ❤️ by <b>Gabriel Correa</b>
        </p>
        <button onClick={this.handleClick}>Testar</button>
      </div>
    );
  }
}

const mapStateToProps = state => ({ payload: state });

export default connect(mapStateToProps)(App);

Спасибо за помощь xD

1 Ответ

0 голосов
/ 26 февраля 2020
yield put(fetchAll(data));

Вы отправляете fetchAll в саге tableCheck. Это вызовет takeLatest в вашей саге root в бесконечном l oop:

yield takeLatest(bookingTypes.GET_ALL, tableCheck)

Вероятно, поэтому вы видите столько запросов.


Решение

Как описано в комментариях:

Вместо этого я бы поделился с помощью fetchAll по крайней мере на fetchAllRequest и fetchAllSuccess (GET_ALL_REQUEST и GET_ALL_SUCCESS). app. js и takeLatest вместо этого используйте fetchAllRequest / GET_ALL_REQUEST. поставить и редуктор использовать взамен fetchAllSuccess / GET_ALL_SUCCESS.

...