moved hooks to separate directories, added stories fallback

This commit is contained in:
2023-05-17 10:46:59 +03:00
parent e9b7a9e32a
commit dc6f8fe8f2
6 changed files with 138 additions and 64 deletions

View File

@ -0,0 +1,5 @@
export { default as useHomeAnnouncementList } from './useHomeAnnouncementList'
export { default as useBook } from './useBook'
export { default as useAuth } from './useAuth'
export { default as useTrashboxes } from './useTrashboxes'
export { default as useAddAnnouncement } from './useAddAnnouncement'

View File

@ -0,0 +1,41 @@
import { useEffect, useState } from "react"
const useFetch = (url, params, initialData) => {
const [data, setData] = useState(initialData)
const [loading, setLoading] = useState(true)
const [error, setError] = useState("")
useEffect(() => {
fetch(url, params)
.then(res => {
if (!res.ok) {
switch (res.status) {
case 401: {
throw new Error("Ошибка авторизации")
}
case 404: {
new Error("Объект не найден")
}
break
default: {
throw new Error("Ошибка ответа от сервера")
}
}
}
return res.json()
})
.then(data => {
setData(data)
setLoading(false)
})
.catch(err => {
setError("Ошибка сети")
setLoading(false)
})
}, [url, params])
return { data, loading, error }
}
export default useFetch

View File

@ -0,0 +1,26 @@
import useFetch from './useFetch'
import { API_URL } from '../../config'
import { removeNull } from '../../utils'
const initialAnnouncements = { list_of_announcements: [], Success: true }
const useHomeAnnouncementList = (filters) => {
const { data, loading, error } = useFetch(
API_URL + '/announcements?' + new URLSearchParams(removeNull(filters)),
null,
initialAnnouncements
)
const annList = data.list_of_announcements
const res = annList.map(ann => ({
...ann,
lat: ann.latitude,
lng: ann.longtitude,
bestBy: ann.best_by
}))
return { data: error ? [] : res, loading, error }
}
export default useHomeAnnouncementList

View File

@ -0,0 +1,34 @@
import { useState, useEffect } from 'react';
function getWindowDimensions() {
const { innerWidth: width, innerHeight: height } = window;
return {
width,
height
};
}
function useStoryDimensions(maxRatio = 16/9) {
const [windowDimensions, setWindowDimensions] = useState(getWindowDimensions())
useEffect(() => {
function handleResize() {
setWindowDimensions(getWindowDimensions());
}
window.addEventListener("resize", handleResize);
return () => window.removeEventListener("resize", handleResize);
}, []);
const height = windowDimensions.height - 56
const ratio = Math.max(maxRatio, height / windowDimensions.width)
return {
height: height,
width: Math.round(height / ratio)
}
}
export default useStoryDimensions