Answer the question
In order to leave comments, you need to log in
Why does the hook not work correctly?
Good day.
There are 2 hooks:
useSessionStorage
const useLocalStorage = (key, initialValue = '') => {
const [value, setValue] = useState(() => {
return sessionStorage.getItem(key) || initialValue;
});
useEffect(() => {
sessionStorage.setItem(key, value);
}, [key, value]);
return [value, setValue];
};
const useFetch = (url) => {
const baseUrl = 'http://localhost:3000';
const [isFetchLoading, setIsFetchLoading] = useState(false);
const [response, setResponse] = useState(null);
const [error, setError] = useState(null);
const [options, setOptions] = useState({});
const [token] = useSessionStorage('token');
const doFetch = useCallback(
(options = {}) => {
if (!options.method) {
options.method = 'GET';
}
options.headers = {
...options.headers,
'Authorization': token ? `Bearer ${token}` : '',
};
if (options.body) {
options.headers = {
'Content-Type': 'application/json',
...options.headers,
};
}
if (options.body) {
options.body = JSON.stringify(options.body);
}
setOptions(options);
setIsFetchLoading(true);
},
[token]
);
useEffect(() => {
let stopGettingResponseAfterDestroy = false;
if (!isFetchLoading) return;
fetch(`${baseUrl}${url}`, options)
.then((res) => res.json())
.then((data) => {
if (!stopGettingResponseAfterDestroy) {
data.errors ? setError(data) : setResponse(data);
}
})
.catch((err) => {
if (!stopGettingResponseAfterDestroy) {
setError(err);
}
})
.finally(() => {
if (!stopGettingResponseAfterDestroy) {
setIsFetchLoading(false);
}
});
return () => {
stopGettingResponseAfterDestroy = true;
};
}, [url, isFetchLoading, options]);
return [{ isFetchLoading, response, error }, doFetch];
};
...
const [token, setToken] = useSessionStorage('token');
const [{ isFetchLoading, response, error }, doFetch] = useFetch('/login');
...
useEffect(() => {
console.log('token useEffect setting value', value);
sessionStorage.setItem(key, value);
setValue(value);
}, [key, value]);
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question