React. При отправке axios-запросов компонент ререндерится слишком много раз (или нет).
использую следующий код:
ХУК useBaseAxios (базовый хук для запросов, будет использоваться внутри другого кастомного хука)
import { useState, useEffect} from 'react';
import axios from 'axios';
const baseAxios = axios.create({
baseURL: 'http://127.0.0.1:8000/api/v1',
});
const useBaseAxios = ({method = "GET", url}) => {
const [data, setData] = useState(null);
const [isLoading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
const controller = new AbortController();
const signal = controller.signal;
const fetchData = async () => {
try {
const response = await baseAxios.request({method, url, signal})
setData(response.data)
} catch (error) {
if (!axios.isCancel(error)){
setError(error)
}
} finally {
setLoading(false)
}
}
if (!data) {
fetchData()
}
return () => {
controller.abort()
}
}, [method, url])
return [data, isLoading, error]
};
export default useBaseAxios;
ХУК useClosestLesson (использует useBaseAxios, используется в компоненте Main)
import useBaseAxios from "./useBaseAxios";
function useClosestLessons() {
const [data, isLoading, error] = useBaseAxios({method: 'GET', url: '/lessons'})
let lessonsSchedule = [];
let currentLesson = {};
if (data) {
lessonsSchedule = [...data]
currentLesson = lessonsSchedule[0]
}
return [lessonsSchedule, currentLesson, isLoading, error]
}
export default useClosestLessons
компонент Main (при его рендерах отображаются консоль логи)
import React from "react";
import './Main.scss';
import useClosestLessons from "../../hooks/fetch-hooks/useClosestLessons";
import { useState, useEffect, useCallback } from "react";
import axios from "axios";
const Main = () => {
const [lessonsSchedule, currentLessons, isLoading, error] = useClosestLessons();
console.log(lessonsSchedule)
console.log(currentLessons)
if(isLoading) return (<p>Загрузка...</p>)
return(...)
НЕ используя strictmode, ожидаемо получаю в консоль null, null; затем нужные массив и объект.
Если его вернуть - получаю следующую картину:
Должно ли так быть и если да, то почему?