Answer the question
In order to leave comments, you need to log in
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])
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;
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
};
};
};
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question