useState does not changing after setstate callback?

Viewed 144

I just want to add error message in error state. But when error occurs setError does not changing means does not adding error message. Back-end giving the error message as json format { "error": "error message" } and if I console log that error that works fine but error state is not updating.

import { useState, useCallback, useRef, useEffect } from 'react';

export const useHttpClient = () => {
    const [ isLoading, setIsLoading ] = useState(false);
    const [ error, setError ] = useState();

    const activeHttpRequests = useRef([]);

    const sendRequest = useCallback(async (url, method = 'GET', body = null, headers = {}) => {
        setIsLoading(true);
        const httpAbortCtrl = new AbortController();
        activeHttpRequests.current.push(httpAbortCtrl);
         try {
            const response = await fetch(url, {
                method,
                body,
                headers,
                signal: httpAbortCtrl.signal
            });
            const responseData = await response.json();
            activeHttpRequests.current = activeHttpRequests.current.filter(
                reqCtrl => reqCtrl !== httpAbortCtrl
            );

            if(!response.ok) {
                throw new Error(responseData.error);
            }

            setIsLoading(false);
            return responseData;
        } catch (e) {
            setError(e.message);
            setIsLoading(false);
            throw e;
        }
    }, []);

     const clearError = () => {
         setError(null);
     };

    useEffect(() => {
        //this runs as cleanup function before next time useEffect run or also when an component use useEffect unmount
        return () => {
            activeHttpRequests.current.forEach(aboutCtr => aboutCtr.abort());
        }
    }, []);

     return { isLoading, error, sendRequest, clearError };
}

1 Answers

As your backend is responding with JSON, that would mean the response status code is probably 200 (successful). Which makes "response.ok" true.

You will have to look at the returned JSON string for valid data or error message.

Related