Y
Y
yumakaev2019-12-25 10:33:09
React
yumakaev, 2019-12-25 10:33:09

How to remove endless API requests?

Hello!
I'm trying to do a search on the elements that I get from the API.
Using useEffect, I connect to service.js (getAllPerson), then I give the answer heroesApiLoaded (this is an action), after that, the reducer adds data to the array, which I take from mapStateToProps (apiHeroes), in state (values) I write the value from the input and compare it with apiHeroes.
My useEffect:

useEffect(() => {
    apiService.getAllPerson()
    .then(data => heroesApiLoaded(data))
  }, [apiHeroes])

My reducer:
const initialState =  {
  promoHeroes: [],
  apiHeroes: [],
  promoLoader: true
};

const reducer = (state = initialState, action) => {
  switch(action.type) {
    case "HEROES_PROMO_LOADED":
      return {
        apiHeroes: [],
        promoHeroes: action.payload,
        promoLoader: false
      };
    case "HEROES_API_LOADED":
      return {
        apiHeroes: action.payload,
        promoHeroes: action.payload,
        promoLoader: false
      }
    default: 
      return state;
  };
};

export default reducer;

service.js
export default class ApiService {
  _url = 'https://swapi.co/api';
  async ApiGetContent(fullUrl) {
    const request = await fetch(`${this._url}${fullUrl}`);

    if(!request.ok) {
      throw new Error(`Ошибка:${request.status}`)
    }
    return await request.json();
  }

  getAllPerson = async () => {
    const res = await this.ApiGetContent(`/people/`);
    return res.results.map(this.transformPerson);
  }

  _extractId(item) {
    const idRegExp = /\/([0-9]*)\/$/;
    return item.url.match(idRegExp)[1];
}

  transformPerson = (res) => {
    return {
        id: this._extractId(res),
        name: res.name,
        gender: res.gender,
        mass: res.mass
    };
  };
};

imLUnYw.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
H
hzzzzl, 2019-12-25
@hzzzzl

useEffect(() => {
apiService.getAllPerson()
.then(data => heroesApiLoaded(data))
}, [ apiHeroes ]) <- useEffect is called every time apiHeroes changes, and it changes every time useEffect is called

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question