A
A
Alexander2020-08-04 23:12:20
JavaScript
Alexander, 2020-08-04 23:12:20

React query hook giving wrong data?

I wrote a hook to get data from the server via Fetch, so as not to write many lines of code each time for the request.

Hook Code
export const useFetch = () => {
    const [loading, setLoading] = useState(false);
    const [response, setResponse] = useState();
    const [error, setError] = useState();

    const request = async (url, method = 'GET', body = null) => {
        setLoading(true);
        try {
            setResponse(null);
            setError(null);

            const response = await fetch(url, {method, body, headers: {
                'Content-Type': 'application/json'
                // 'Content-Type': 'application/x-www-form-urlencoded',
            }});
 
            setLoading(false);

            if (response.ok) {
                const json = await response.json();
                setResponse(json);
            }

            if(!response.ok) {
                throw new Error(response.statusText);
            }
        } catch (e) {
            setError(e.message);
        }
    };

    const clearError = () => setError(null);
    return { loading, error, request, response, clearError };
};


There was a strange problem: the data that the hook returns is late.

I use hook in one component:
Component code

const getThread = async () => {
        try {
            await request(`/api/boards/${boardName}/${threadName}`);

            if (error) {
           // Выполняется при ошибке
            }
        } catch (e) {
            console.error(e.message);
        }
    }



A successful request returns undefined in both Error and Response. On the next request, the hook returns the correct data from the previous request. If there was an error on the first request, the hook will only return it on the next request, even if there was a successful request.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vovash, 2020-08-04
@V0vash

Wrap it in the useCallback hook.
it will be something like this

const request =  useCallback(async (url, method = 'GET', body = null, headers ={}) => {
        setLoading(true)
        try{
            if (body) {
                body = JSON.stringify(body)
                headers['Content-Type'] = 'application/json'
            }

            const response = await fetch(url, {method, body, headers})
            const data = await response.json()

            if (! response.ok){
                throw new Error(data.message || 'Что-то пошло не так')
            }

            setLoading(false)

            return data
        }catch(e){
            setLoading(false)
            setError(e.message)
            throw e
        }
    }, [])

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question