Notice: file_put_contents(): Write of 2707 bytes failed with errno=28 No space left on device in /var/www/tgoop/post.php on line 50

Warning: file_put_contents(): Only 16384 of 19091 bytes written, possibly out of free disk space in /var/www/tgoop/post.php on line 50
React JS@react_tg P.424
REACT_TG Telegram 424
💻 Проверь свои скиллы — задача по написанию hook для загрузки данных

На первой итерации решение может выглядеть как-то так:
function useFetch(url) {
const [data, setData] = useState(null);

useEffect(() => {
fetch(url)
.then((res) => res.json())
.then((respData) => setData(respData));
}, []);

return data;
}

В этом коде не хватает зависимости. Если url изменится, то запроса данных не произойдет.

Дальше код может стать таким:
function useFetch(url) {
const [data, setData] = useState(null);

useEffect(() => {
setData(null); // не забыть сбросить данные перед загрузкой
fetch(url)
.then((res) => res.json())
.then((respData) => setData(respData));
}, [url]); // <-- не забыть зависимость

return data;
}

На этом этапе можно остановиться, и подумать, как улучшить этот hook.

Пропустим ещё несколько итераций, и финальный код, который можно считать неплохим решением, выглядит так:
function useFetch(url) {
const [data, setData] = useState(null);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState(null);

useEffect(() => {
// флаг отмены
let cancelled = false;

setIsLoading(true);
setData(null);
setError(null);
fetch(url)
.then((res) => res.json())
.then((respData) => {
if (!cancelled) setData(respData);
})
.catch((e) => {
if (!cancelled) setError(e);
})
.finally(() => {
if (!cancelled) setIsLoading(false);
});

return () => {
// выставим признак того, что запрос отменен
cancelled = true;
};
}, [url]);

return [data, isLoading, error];
}


Эта задачка позволяет проверить понимание устройства рендеринга React, как устроено хранение состояния, когда происходят перерисовки, как заставить компонент перерисоваться в ответ на асинхронное событие, как устроена "очистка (cleanup) эффекта", как работают сайд-эффекты.

@react_tg
Please open Telegram to view this post
VIEW IN TELEGRAM
👍29🔥43



tgoop.com/react_tg/424
Create:
Last Update:

💻 Проверь свои скиллы — задача по написанию hook для загрузки данных

На первой итерации решение может выглядеть как-то так:

function useFetch(url) {
const [data, setData] = useState(null);

useEffect(() => {
fetch(url)
.then((res) => res.json())
.then((respData) => setData(respData));
}, []);

return data;
}

В этом коде не хватает зависимости. Если url изменится, то запроса данных не произойдет.

Дальше код может стать таким:
function useFetch(url) {
const [data, setData] = useState(null);

useEffect(() => {
setData(null); // не забыть сбросить данные перед загрузкой
fetch(url)
.then((res) => res.json())
.then((respData) => setData(respData));
}, [url]); // <-- не забыть зависимость

return data;
}

На этом этапе можно остановиться, и подумать, как улучшить этот hook.

Пропустим ещё несколько итераций, и финальный код, который можно считать неплохим решением, выглядит так:
function useFetch(url) {
const [data, setData] = useState(null);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState(null);

useEffect(() => {
// флаг отмены
let cancelled = false;

setIsLoading(true);
setData(null);
setError(null);
fetch(url)
.then((res) => res.json())
.then((respData) => {
if (!cancelled) setData(respData);
})
.catch((e) => {
if (!cancelled) setError(e);
})
.finally(() => {
if (!cancelled) setIsLoading(false);
});

return () => {
// выставим признак того, что запрос отменен
cancelled = true;
};
}, [url]);

return [data, isLoading, error];
}


Эта задачка позволяет проверить понимание устройства рендеринга React, как устроено хранение состояния, когда происходят перерисовки, как заставить компонент перерисоваться в ответ на асинхронное событие, как устроена "очистка (cleanup) эффекта", как работают сайд-эффекты.

@react_tg

BY React JS




Share with your friend now:
tgoop.com/react_tg/424

View MORE
Open in Telegram


Telegram News

Date: |

With the “Bear Market Screaming Therapy Group,” we’ve now transcended language. Just at this time, Bitcoin and the broader crypto market have dropped to new 2022 lows. The Bitcoin price has tanked 10 percent dropping to $20,000. On the other hand, the altcoin space is witnessing even more brutal correction. Bitcoin has dropped nearly 60 percent year-to-date and more than 70 percent since its all-time high in November 2021. While the character limit is 255, try to fit into 200 characters. This way, users will be able to take in your text fast and efficiently. Reveal the essence of your channel and provide contact information. For example, you can add a bot name, link to your pricing plans, etc. During a meeting with the president of the Supreme Electoral Court (TSE) on June 6, Telegram's Vice President Ilya Perekopsky announced the initiatives. According to the executive, Brazil is the first country in the world where Telegram is introducing the features, which could be expanded to other countries facing threats to democracy through the dissemination of false content. Healing through screaming therapy
from us


Telegram React JS
FROM American