This is the relevant part of my code:
const [savedItems, setSavedItems] = useState([]);
const [savedIds, setSavedIds] = useState([]);
useEffect(() => {
let isMounted = true;
if (props.token) {
fetch(url, {
method: 'GET',
withCredentials: true,
credentials: 'include',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Token ' + props.token,
}
})
.then((response) => {
return response.json()
})
.then((json) => {
if (isMounted)
setSavedItems(json)
})
.then(() => {
const idsArray = savedItems.map((item) => item.site_id)
setSavedIds(idsArray)
})
.catch((error) => console.error(error))
.finally(() => isMounted = false);
}
}, []);
In this part of code, I fetch data from a website and I store it in savedItems
. The data looks like this:
[{"site_id":"3350","user":234},
{"site_id":"857","user":234},
{"site_id":"295","user":234},
{"site_id":"674","user":234}]
I can successfully store the fetched data into the savedItems
state variable. Then, I just want to extract the value site_id
for each item and store them into an array. So I would like to have an array like this:
[3350,857,295,674]
That's what I'm trying to achieve with this part of code:
const idsArray = savedItems.map((item) => item.site_id)
setSavedIds(idsArray)
However, if I later try to render the savedIds
state variable, it appears to always be empty.