Home > Software engineering >  How to keep track of multiple api calls in react?
How to keep track of multiple api calls in react?

Time:01-06

I have a react application when i have three components that each of them uses useAxios.js hook to make an api call to fetch data (three different endpoints) and then returns data, error, loading states, now i want to make a loading screen while the app is loading, i want to show the loading screen while the components fetch data from the server. i am not sure how to keep track of the three calls when each of them have separate loading states.

how to implement a loading screen for that application?

i am not sure if i can use useContext to make a global state or using useReducer

CodePudding user response:

If you app got simple state:

  • Just lift up your loading state to parent component and pass to children as props.

If you got complex state in your app:
Option1 - You can create some react context for handle loading state and use useContext in any child component.
Option2 - Use state management such as redux or react-query for handle your loading state.

CodePudding user response:

const useFetch = (url) => {
    const [data, setData] = useState(null);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);

    useEffect(() => {
        axios.get(url)
            .then((res) => {
                setData(res.data)
                setLoading(false)
            }).catch(err => {
                setError(err)
                setLoading(false)
            })
    }, [url]);

    return { data, loading, error }
};

export default useFetch;

You can use this custom hook in your components like this for dynamic use

const { data, loading, errors } = useFetch('localhost:3000/api/user')

In this way you can easily track all the request separately and can implement your loader accodingly

loading ? <Loader /> : <Random />
  • Related