ppowell777
Well-Known Coder
I have a multi-use React Hook function, useGetData({url}), that takes a url, does a Fetch API, then returns the resulting JSON array string for further processing in other functions and components. However, useGetData({url}) constantly returns null every time, no matter what I do.
I am using it in this other function (will be used within multiple functions and components in the future), and this constantly returns null which breaks JSON.parse:
I am too new to React framework to know how to fix this issue. Can anyone please help?
Thanks
JavaScript:
import { useEffect, useState } from 'react';
import DOMPurify from 'dompurify';
// React function non-component due to naming convention
export const useGetData = ({ url }) => {
console.log(`url = ${url}`); // Returns the provided URL so all fine here
const [text, setText] = useState('');
const [loading, setLoading] = useState(true);
useEffect(() => {
const controller = new AbortController();
const timeout = setTimeout(() => {
controller.abort();
}, 5000);
fetch(url, {
signal: controller.signal
})
.then(response => {
clearTimeout(timeout);
if (response.ok && response.status === 200) {
return response.text();
} else if (response.status >= 400) {
return Promise.reject(response.statusText);
}
})
.then(async myText => {
setText(await myText);
setLoading(false);
})
.catch(error => {
console.error(error);
});
});
if (loading) {
console.log('empty');
return '';
} else {
console.log('not empty');
return DOMPurify.sanitize(text);
}
}
I am using it in this other function (will be used within multiple functions and components in the future), and this constantly returns null which breaks JSON.parse:
JavaScript:
const useGetStateOptions = () => {
const url = 'http://localhost:8080/react/states.json'
let stateJsonArrayStr = useGetData({url});
const [html, setHtml] = useState('');
const [loading, setLoading] = useState(true);
useEffect(() => {
let optionHTML = '';
const stateJsonArray = JSON.parse(stateJsonArrayStr.trim());
if (typeof stateJsonArray === 'undefined' || stateJsonArray === null || stateJsonArray.length === 0) {
console.error('state JSON array is undefined');
} else {
setLoading(false);
stateJsonArray.forEach((element) => {
optionHTML += `<option value="${element.urlEnding}">${element.name}</option>\n`;
});
setHtml(optionHTML);
}
}, [stateJsonArrayStr]);
if (loading) {
return '';
} else {
return DOMPurify.sanitize(html);
}
};
I am too new to React framework to know how to fix this issue. Can anyone please help?
Thanks