Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Dmitriy-8-Kireev/139bbb1437dbb92745b391fd6e958b31 to your computer and use it in GitHub Desktop.
Save Dmitriy-8-Kireev/139bbb1437dbb92745b391fd6e958b31 to your computer and use it in GitHub Desktop.
Мелочи по серверной части
// просто fetch
fetch("https://swapi.co/api/people/5")
.then(res => {
return res.json();
});
.then((body) => {
console.log(body)
})
// Асинхронная ф-ия
const getResourse = async url => {
const res = await fetch(url);
console.log("RES", res);
const bodyJson = await res.json();
console.log("BODY-JSON", bodyJson);
return bodyJson;
};
getResourse("https://swapi.co/api/people/5").then(bodyJson => {
return console.log(bodyJson);
// Реализована возможность поймать 404
const getResource2 = async url => {
const res = await fetch(url);
if (!res.ok) {
throw new Error(`Could not fetch ${url}` + `, received ${res.status}`);
}
const bodyJson = await res.json();
return bodyJson;
};
getResource2("https://swapi.co/api/people/555")
.then(b => {
return console.log(b);
})
.catch(err => {
console.error("Error");
});
});
// Инкапсуляция класс
export default class SwapiService {
_apiBase = "https://swapi.co/api";
async getResource(url) {
const res = await fetch(`${this._apiBase}${url}`);
if (!res.ok) {
throw new Error(`Could not fetch ${url}` + `, received ${res.status}`);
}
return await res.json();
}
async getAllPeople() {
const res = await this.getResource(`/people/`);
return res.results;
}
getPerson(id) {
return this.getResource(`/people/${id}/`);
}
async getAllPlanets() {
const res = await this.getResource(`/planets/`);
return res.results;
}
getPlanet(id) {
return this.getResource(`/planets/${id}/`);
}
async getAllStarships() {
const res = await this.getResource(`/starships/`);
return res.results;
}
getStarship(id) {
return this.getResource(`/starships/${id}/`);
}
}
// Получение данных с сервера Создание компонента, который получает данные от сервера (..--55--..)
import React, { Component } from "react";
import "./random-planet.css";
import SwapiService from "../../services/swapi-service";
export default class RandomPlanet extends Component {
Server = new SwapiService();
state = {
id: null,
name: null,
population: null,
period: null,
diameter: null
};
// Данные с сервера получаем в componentDidMount() (..--56--..)
componentDidMount() {
this.getServerPlanet();
}
// В then() обновляем состояние компонента
getServerPlanet = () => {
const id = Math.floor(Math.random() * 15) + 3;
this.Server
.getPlanet(id)
.then(planet => {
this.setState({
id,
name: planet.name,
population: planet.population,
period: planet.rotation_period,
diameter: planet.diameter
});
});
};
render() {
const { id, name, population, period, diameter } = this.state;
return (
<div className="random-planet jumbotron rounded">
<img
className="planet-image"
src={`https://starwars-visualguide.com/assets/img/planets/${id}.jpg`}
/>
<div>
<h4>{name}</h4>
<ul className="list-group list-group-flush">
<li className="list-group-item">
<span className="term">Population</span>
<span>{population}</span>
</li>
<li className="list-group-item">
<span className="term">Period</span>
<span>{period}</span>
</li>
<li className="list-group-item">
<span className="term">Diameter</span>
<span>{diameter}</span>
</li>
</ul>
</div>
</div>
);
}
}
------
export default class SwapiService {
_apiBase = "https://swapi.co/api";
async getResource(url) {
const res = await fetch(`${this._apiBase}${url}`);
if (!res.ok) {
throw new Error(`Could not fetch ${url}` + `, received ${res.status}`);
}
return await res.json();
}
getPlanet(id) {
return this.getResource(`/planets/${id}/`);
}
}
//
ПРАВИЛА
1) Изолируйте код, который обрабатывает данные
2) Отделяйте модель данных Api от модели данных приложения
3) Такая практика чаще применяется для крупных проектов со сложными моделями данных, которые могут изменяться
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment