Функция callback, создающая элемент в новом массиве, принимает три аргумента:Array.prototype.map()
currentValue
Текущий обрабатываемый элемент массива.
index Необязательный
Индекс текущего обрабатываемого элемента в массиве.
array Необязательный
Массив, по которому осуществляется проход.
.then(response => console.log(response))
{
"status": {
"timestamp": "2021-06-28T05:54:55.250Z",
"error_code": 0,
"elapsed": 28,
"credit_count": 1,
"total_count": 5475
},
"data": [
{
"id": 1,
"name": "Bitcoin",
"symbol": "BTC",
"slug": "bitcoin",
"num_market_pairs": 9210,
"date_added": "2013-04-28T00:00:00.000Z",
"tags": [
"mineable",
"pow",
"sha-256",
"store-of-value",
"state-channels",
"coinbase-ventures-portfolio",
"three-arrows-capital-portfolio",
"polychain-capital-portfolio",
"binance-labs-portfolio",
"arrington-xrp-capital",
"blockchain-capital-portfolio",
"boostvc-portfolio",
"cms-holdings-portfolio",
"dcg-portfolio",
"dragonfly-capital-portfolio",
"electric-capital-portfolio",
"fabric-ventures-portfolio",
"framework-ventures",
"galaxy-digital-portfolio",
"huobi-capital",
"alameda-research-portfolio",
"a16z-portfolio",
"1confirmation-portfolio",
"winklevoss-capital",
"usv-portfolio",
"placeholder-ventures-portfolio",
"pantera-capital-portfolio",
"multicoin-capital-portfolio",
"paradigm-xzy-screener"
],
"max_supply": 21000000,
"circulating_supply": 18743737,
"total_supply": 18743737,
"cmc_rank": 1,
"last_updated": "2021-06-28T05:54:02.000Z",
"quote": {
"USD": {
"price": 34489.91295375669,
"volume_24h": 33231566302.9618,
"percent_change_1h": 0.24623143,
"percent_change_24h": 4.72866241,
"percent_change_7d": 0.0385825,
"percent_change_30d": -6.57806083,
"percent_change_60d": -36.08177402,
"percent_change_90d": -40.16259997,
"market_cap": 646469857558.1086,
"last_updated": "2021-06-28T05:54:02.000Z"
}
}
},
{
"id": 1027,
"name": "Ethereum",
"symbol": "ETH",
"slug": "ethereum",
"num_market_pairs": 6005,
"date_added": "2015-08-07T00:00:00.000Z",
"tags": [
"mineable",
"pow",
"smart-contracts",
"ethereum",
"coinbase-ventures-portfolio",
"three-arrows-capital-portfolio",
"polychain-capital-portfolio",
"binance-labs-portfolio",
"arrington-xrp-capital",
"blockchain-capital-portfolio",
"boostvc-portfolio",
"cms-holdings-portfolio",
"dcg-portfolio",
"dragonfly-capital-portfolio",
"electric-capital-portfolio",
"fabric-ventures-portfolio",
"framework-ventures",
"hashkey-capital-portfolio",
"kinetic-capital",
"huobi-capital",
"alameda-research-portfolio",
"a16z-portfolio",
"1confirmation-portfolio",
"winklevoss-capital",
"usv-portfolio",
"placeholder-ventures-portfolio",
"pantera-capital-portfolio",
"multicoin-capital-portfolio",
"paradigm-xzy-screener"
],
"circulating_supply": 116469137.499,
"total_supply": 116469137.499,
"cmc_rank": 2,
"last_updated": "2021-06-28T05:54:02.000Z",
"quote": {
"USD": {
"price": 1972.9974245462824,
"volume_24h": 19489435867.08539,
"percent_change_1h": -0.03164063,
"percent_change_24h": 5.36554092,
"percent_change_7d": -7.36312666,
"percent_change_30d": -22.4570674,
"percent_change_60d": -27.41396336,
"percent_change_90d": 9.21290472,
"market_cap": 229793308324.65384,
"last_updated": "2021-06-28T05:54:02.000Z"
}
}
},
{
"id": 825,
"name": "Tether",
"symbol": "USDT",
"slug": "tether",
"num_market_pairs": 13711,
"date_added": "2015-02-25T00:00:00.000Z",
"tags": [
"payments",
"stablecoin",
"stablecoin-asset-backed",
"solana-ecosystem"
],
"circulating_supply": 62534142511.11169,
"total_supply": 64471767616.826355,
"platform": {
"id": 1027,
"name": "Ethereum",
"symbol": "ETH",
"slug": "ethereum",
"token_address": "0xdac17f958d2ee523a2206206994597c13d831ec7"
},
"cmc_rank": 3,
"last_updated": "2021-06-28T05:53:08.000Z",
"quote": {
"USD": {
"price": 1.00023604778902,
"volume_24h": 50665651395.52314,
"percent_change_1h": -0.00327685,
"percent_change_24h": -0.11177658,
"percent_change_7d": -0.14175554,
"percent_change_30d": -0.07861614,
"percent_change_60d": 0.01010439,
"percent_change_90d": -0.01064075,
"market_cap": 62548903557.1897,
"last_updated": "2021-06-28T05:53:08.000Z"
}
}
},
{
"id": 1839,
"name": "Binance Coin",
"symbol": "BNB",
"slug": "binance-coin",
"num_market_pairs": 570,
"date_added": "2017-07-25T00:00:00.000Z",
"tags": [
"marketplace",
"centralized-exchange",
"payments",
"binance-smart-chain",
"alameda-research-portfolio",
"multicoin-capital-portfolio"
]
}
]
}
using System.Text.Json;
using System.Text.Json.Serialization;
public class Status
{
[JsonPropertyName("timestamp")]
public DateTime Timestamp { get; set; }
[JsonPropertyName("error_code")]
public int ErrorCode { get; set; }
[JsonPropertyName("elapsed")]
public int Elapsed { get; set; }
[JsonPropertyName("credit_count")]
public int CreditCount { get; set; }
[JsonPropertyName("total_count")]
public int TotalCount { get; set; }
}
public class QuoteForCurrency
{
[JsonPropertyName("price")]
public decimal Price { get; set; }
[JsonPropertyName("volume_24h")]
public decimal Volume24h { get; set; }
[JsonPropertyName("percent_change_1h")]
public decimal PercentChange1h { get; set; }
[JsonPropertyName("percent_change_24h")]
public decimal PercentChange24h { get; set; }
[JsonPropertyName("percent_change_7d")]
public decimal PercentChange7d { get; set; }
[JsonPropertyName("percent_change_30d")]
public decimal PercentChange30d { get; set; }
[JsonPropertyName("percent_change_60d")]
public decimal PercentChange60d { get; set; }
[JsonPropertyName("percent_change_90d")]
public decimal PercentChange90d { get; set; }
[JsonPropertyName("market_cap")]
public decimal MarketCap { get; set; }
[JsonPropertyName("last_updated")]
public DateTime LastUpdated { get; set; }
}
public class Platform
{
[JsonPropertyName("id")]
public int Id { get; set; }
[JsonPropertyName("name")]
public string Name { get; set; }
[JsonPropertyName("symbol")]
public string Symbol { get; set; }
[JsonPropertyName("slug")]
public string Slug { get; set; }
[JsonPropertyName("token_address")]
public string TokenAddress { get; set; }
}
public class Item
{
[JsonPropertyName("id")]
public int Id { get; set; }
[JsonPropertyName("name")]
public string Name { get; set; }
[JsonPropertyName("symbol")]
public string Symbol { get; set; }
[JsonPropertyName("slug")]
public string Slug { get; set; }
[JsonPropertyName("num_market_pairs")]
public int NumMarketPairs { get; set; }
[JsonPropertyName("date_added")]
public DateTime DateAdded { get; set; }
[JsonPropertyName("tags")]
public List<string> Tags { get; set; }
[JsonPropertyName("max_supply")]
public int MaxSupply { get; set; }
[JsonPropertyName("circulating_supply")]
public decimal CirculatingSupply { get; set; }
[JsonPropertyName("total_supply")]
public decimal TotalSupply { get; set; }
[JsonPropertyName("cmc_rank")]
public int CmcRank { get; set; }
[JsonPropertyName("last_updated")]
public DateTime LastUpdated { get; set; }
[JsonPropertyName("quote")]
public Dictionary<string, QuoteForCurrency> Quote { get; set; }
[JsonPropertyName("platform")]
public Platform Platform { get; set; }
}
public class Response
{
[JsonPropertyName("status")]
public Status Status { get; set; }
[JsonPropertyName("data")]
public List<Item> Data { get; set; }
}
var json = "{}"; // тут твой ответ json из ответа
var responseData = JsonSerializer.Deserialize<Response>(json);
const date = new Date(str.replace(/\S+/, m => m.split('.').reverse().join('-')));
const date = new Date(str.replace(/(\d+)\.(\d+)\.(\d+)/, '$3-$2-$1'));
const [ day, month, year, hours, minutes, seconds ] = str.split(/\D/);
const date = new Date(year, month - 1, day, hours, minutes, seconds);
const date = dayjs(str, 'DD.MM.YYYY HH:mm:ss').toDate();
Если на js можно использовать sessionStorage, но говорят так делать не правильно.
Раз так, тогда как отслеживать их, постоянно отправлять гет запрос?
То есть получается, что бы взаимодействовать с сессией нужно постоянно использовать ajax, как по мне sessionStorage использовать куда дешевле...
import React, { useCallback } from 'react';
import { Formik, Form, useField } from 'formik';
import * as yup from 'yup';
const initialValues = {
firstName: '',
lastName: '',
nickName: '',
email: '',
password: '',
confirmPassword: ''
};
const validationSchema = yup.object().shape({
firstName: yup.string().required('Имя является обязательным'),
lastName: yup.string().required('Фамилия является обязательной'),
nickName: yup.string().required('Имя пользователя является обязательным'),
email: yup
.string()
.email('Введенное значение не является почтой')
.required('Почта является обязательной'),
password: yup
.string()
.min(8, 'Минимальная длина пароля 8 символов')
.required('Пароль является обязательным'),
confirmPassword: yup
.string()
.oneOf([yup.ref('password'), null], 'Пароли не совпадают')
.min(8, 'Минимальная длина пароля 8 символов')
.required('Пароль является обязательным')
});
const ExampleField = ({ name, label, ...props }) => {
const [field, meta, helpers] = useField(name);
return (
<label>
{label}
<input
name={name}
value={field.value}
onChange={field.onChange}
onBlur={field.onBlur}
{...props}
/>
{meta.error !== undefined && meta.touched && <div>{meta.error}</div>}
</label>
);
};
const ExampleForm = () => {
const handleSubmit = useCallback((values, helpers) => {
console.log(values);
helpers.setSubmitting(false);
}, []);
return (
<Formik
initialValues={initialValues}
validationSchema={validationSchema}
validationOnBlur
onSubmit={handleSubmit}
>
{({ values, errors, touched, isValid, isSubmitting }) => (
<Form>
<ExampleField label="Имя" name="firstName" />
<ExampleField label="Фамилия" name="lastName" />
<ExampleField label="Имя пользователя" name="nickName" />
<ExampleField label="Почта" type="email" name="email" />
<ExampleField label="Пароль" type="password" name="password" />
<ExampleField label="Подтверждение пароля" type="password" name="confirmPassword" />
<button type="submit" disabled={!isValid || isSubmitting}>
Отправить
</button>
<pre>{JSON.stringify({ values, errors, touched }, null, 2)}</pre>
</Form>
)}
</Formik>
);
};
развернуть собственный сервер-хранилище (эта идея была практически сразу откинута)
// в data передаются параметры POST (ключ - значение)
// если надо загрузить файл - передаётся в file
internal static string Post(string url, Dictionary<string, string> data, FileUploadData file = null)
{
string ServerResponse = null;
HttpWebRequest wrq = (HttpWebRequest)HttpWebRequest.Create(url);
wrq.Method = WebRequestMethods.Http.Post;
wrq.UserAgent = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name +
System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
wrq.Timeout = 600000;
try
{
// Это на случай использования прокси, можно выкинуть
if (Config.UseProxy)
{
WebProxy proxy = new WebProxy(Config.ProxyAddress, Config.ProxyPort);
if (Config.ProxyLogin != string.Empty || Config.ProxyPass != string.Empty)
{
proxy.Credentials = new NetworkCredential(Config.ProxyLogin, Config.ProxyPass);
proxy.UseDefaultCredentials = false;
}
else
{
proxy.UseDefaultCredentials = true;
}
}
if (null == file) // проверяем, надо ли загружать файл на сервер
{
wrq.ContentType = "application/x-www-form-urlencoded";
Stream requestStream = wrq.GetRequestStream();
List<string> keydata = new List<string>();
foreach (string key in data.Keys)
{
keydata.Add($"{HttpUtility.UrlEncode(key)}={HttpUtility.UrlEncode(data[key])}");
}
WriteToStream(requestStream, string.Join("&", keydata));
requestStream.Flush();
}
else
{
// Формируем multipart/form-data (отправка данных с формы)
string boundary = "----------" + DateTime.Now.Ticks.ToString("x");
wrq.ContentType = "multipart/form-data; boundary =" + boundary;
Stream requestStream = wrq.GetRequestStream();
WriteMultipartForm(requestStream, boundary, data, file);
}
// Посылаем данные на сервер и ждём ответа
wrq.BeginGetResponse(a =>
{
try
{
WebResponse resp = wrq.EndGetResponse(a);
Stream respStr = resp.GetResponseStream();
using (StreamReader sr = new StreamReader(respStr))
{
ServerResponse = sr.ReadToEnd();
} // using sr
} // try
catch (Exception ex)
{
Logger.LogError("Transport.Post", Globalizer.ID_Transport_Request_executing_error, ex);
} // catch
}, null);
} // try
catch(Exception ex)
{
Logger.LogError("Transport.Post", Globalizer.ID_Transport_Could_not_connect_to_server, ex);
return null;
}
return ServerResponse;
} // Post
private static void WriteMultipartForm(Stream s, string boundary, Dictionary<string, string> data, FileUploadData file)
{
/// The first boundary
byte[] boundarybytes = Encoding.UTF8.GetBytes("--" + boundary + "\r\n");
/// the last boundary.
byte[] trailer = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");
/// the form data, properly formatted
string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
/// the form-data file upload, properly formatted
string fileheaderTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\";\r\nContent-Type: {2}\r\n\r\n";
/// Added to track if we need a CRLF or not.
bool bNeedsCRLF = false;
if (data != null)
{
foreach (string key in data.Keys)
{
/// if we need to drop a CRLF, do that.
if (bNeedsCRLF)
WriteToStream(s, "\r\n");
/// Write the boundary.
WriteToStream(s, boundarybytes);
/// Write the key.
WriteToStream(s, string.Format(formdataTemplate, key, data[key]));
bNeedsCRLF = true;
}
}
/// If we don't have keys, we don't need a crlf.
if (bNeedsCRLF)
WriteToStream(s, "\r\n");
WriteToStream(s, boundarybytes);
WriteToStream(s, string.Format(fileheaderTemplate, file.FieldName, file.Filename, file.ContentType));
/// Write the file data to the stream.
WriteToStream(s, file.FileData);
WriteToStream(s, trailer);
}
private static void WriteToStream(Stream s, string txt)
{
byte[] bytes = Encoding.UTF8.GetBytes(txt);
s.Write(bytes, 0, bytes.Length);
} // WriteToStream