0

I am using custom hook that wraps up fetch api to pull data from endpoints. However, response of totally unrelated request are being mismatched, meaning response of one api is being injected into another request:

This is how I am making use of fetchAPI:

export const useFetch = (url, requestId, body) => {
    const [state, setState] = useState({isLoading: true, data: []})
    const [version, setVersion] = useState(0)

    const getData = async () => {
        const response = await fetch(url, {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(body),
            cache: 'no-store' // disable caching
        });
        const json = await response.json() 
        if (response.status === 200)
            return json
        else throw new Error(`Server Exception occurred. Status code: ${response.status} & Exception: ${json.exception}`)
    }

    useEffect(() => {
        setState({isLoading: true, data: []})
        getData()
            .then((data) => {
                setState(previousState => {
                    return { ...previousState, isLoading: false, data: data }
                });
            })
            .catch((err) => {
                console.log(err)
                addNotification(requestId, 'danger', 'Error', 'An error occurred.', 'top-right')
                setState(previousState => {
                    return { ...previousState, isLoading: false, data: [] }
                });
                // setError(true)
            }).finally(() => {
                console.log(`${requestId} completed...`)
        });
    }, [version]);

    return {isLoading: state.isLoading, data: state.data, version, setVersion}
}

Here's how the hook is being used:

const {isLoading, data} = useFetch(URL_GET_SESSION.constructUrl, 'GET_SESSION', {})

Although I have also used cache: 'no-store' and tried making the request unique by appending ?requestId=requestId, I am still able to replicate the issue sporadically.

What could be the reason for this?

Is there an issue with the implementation itself. I am yet to embed AbortController.

0 Answers0