How to use fetch/axios call api get data in react is right?

Discussão em 'Angular' iniciado por 鄭宇紹, Novembro 18, 2024.

  1. 鄭宇紹

    鄭宇紹 Guest

    I have been learning React with TypeScript for a while now and have a question about fetching server data in React.

    In Angular 2, fetching server data using a service is straightforward and easy to understand in demos. However, in React, there are many examples that use different approaches such as Redux, Saga, or Context, and I am unsure which approach is the most appropriate to follow.

    Below is an example using ContextProvider for fetching server data

    useEffect(()=>{
    const searchResults = async ()=>{
    const resultUrl = `${API_URL}users/all?page=${page}&pageSize=${pageSize}&keyword=${keyword}`;
    const res = await axios.get<Page<User[]>>(resultUrl);
    if (res.status===200) {
    setResult(prevResult => ({
    page: res.data.page,
    pageSize: res.data.pageSize,
    total: res.data.total,
    totalPages: res.data.totalPages,
    data: page === 1 ? res.data.data : prevResult.data.concat(res.data.data),
    }));
    }
    };
    searchResults();
    },[page,pageSize,keyword]);


    anyone can get example and describe why doing or useing this follow. just let me be cearfully react codeing style.

    Continue reading...

Compartilhe esta Página