zhang
2025-05-20 1313906bb1eb983d3beece810035e7fc28d6a92f
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import { useState, useEffect, useCallback } from 'react';
import { debounce } from 'lodash';
import request from '@/utils/request';
 
const useCoolHook = (url, label) => {
    const [options, setOptions] = useState([]);
    const [inputValue, setInputValue] = useState('');
 
    const fetchData = async (condition) => {
        try {
            const res = await request.post(url, {
                condition: condition,
                pageSize: 20
            }).catch(error => {
                console.error(error.message);
            });
            const { code, msg, data: { records } } = res.data;
            if (code === 200) {
                setOptions(records.map(item => ({
                    label: item[label],
                    id: item.id
                })))
            } else {
                console.error(msg);
                setOptions([]);
            }
        } catch (error) {
            console.error(error.message);
            setOptions([]);
        }
    }
 
    const debouncedFetch = useCallback(debounce(fetchData, 300), [url]);
 
    useEffect(() => {
        // console.log(inputValue, url)
        // if (inputValue) {
        //     debouncedFetch(inputValue);
        // } else {
        //     setOptions([]);
        // }
        debouncedFetch(inputValue);
    }, [inputValue, debouncedFetch]);
 
    const resetInput = () => setInputValue('');
 
    return {
        options,
        setInputValue,
        resetInput,
    };
}
 
export default useCoolHook;