Answer the question
In order to leave comments, you need to log in
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.
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 };
};
const getThread = async () => {
try {
await request(`/api/boards/${boardName}/${threadName}`);
if (error) {
// Выполняется при ошибке
}
} catch (e) {
console.error(e.message);
}
}
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question