I created a useState hook to store the ID fetching from the first function., and the initial value of the hook is an empty string(''). But the problem is when I save the file two times the hook stores the ID that I have fetched otherwise it is completely empty.
const [loading, setLoading] = useState(true);
const [data, setData] = useState([]);
const [id, setId] = useState(' ');
const getCMSID = () => {
let url = `${URL}/store-api/category`;
let getId = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
'sw-access-key': `${API_KEY}`,
},
};
fetch(url, getId)
.then(res => res.json())
.then(json => setId(json.elements[0].cmsPageId))
.catch(err => console.error('error:' + err));
const getCMSPage = () => {
const cmsUrl = `${URL}/store-api/cms/${id}`;
let getcms = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
'sw-access-key': `${API_KEY}`,
},
};
fetch(cmsUrl, getcms)
.then(res => res.json())
.then(json => {
setData(json.sections);
setLoading(false);
})
.catch(err => console.error('Error:' + err));
};
getCMSPage();
};
useEffect(() => {
getCMSID();
}, []);