Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
344 views
in Technique[技术] by (71.8m points)

javascript - How to fetch a data without using useffect or setTimeout and add loader in react hooks

DETAIL*

const Detail = (props) {

    const { getLatest, getAll } = useRoom();
    const [ rowData, setRowData ] = useState([]);
    const [ state, setState ] = useState([]);
    
    useEffect(() => {
        const fetchData = async () => {
            getLatest(PARAMS).then((res) => setState(res['data'].data));
            getAll({length: 9999}).then((res) => setRowData(res['data'].data));
        }
        fetchData();
    }, []);

     return (
{state &&
                state.map((res, i) => (
                    <div key={i} className="w-full px-2 flex rounded justify-center items-center p-2 m-1 bg-white">
                        <Room item={res}  />
                    </div>
                ))}
    )
    }
    
export default Detail;

What I'm trying to do here is to add a loader also my problem is when I didn't use the setTimeout I'm getting error which is Request failed with status code 500. but when I added the setTimeout there's no error.

setTimeout(() => {...fetchData }

API CALLING

getLatest: (params?: object) => Axios.get(`${API_URL}/latest` + (params ? getQueryParams(params) : ''))

HERE's the error when reload the page. enter image description here

question from:https://stackoverflow.com/questions/65894632/how-to-fetch-a-data-without-using-useffect-or-settimeout-and-add-loader-in-react

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You're not really doing anything with the async function. The point of using an async function is that you use await inside to wait for the server's response. Try using await instead of using then with the requests that you're making to the server. I believe something like this will work:

useEffect(() => {
    const fetchData = async () => {
        let res = await getLatest(PARAMS);
        setState(res['data'].data)
        let resAll = await getAll({length: 9999});
        setRowData(resAll['data'].data)
    }
    fetchData();
}, []);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...