1

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.

Janez Kuhar
  • 3,705
  • 4
  • 22
  • 45
Damian
  • 155
  • 1
  • 10

1 Answers1

2

You can't update state and immediately use the updated value. Refer to: useState set method not reflecting change immediately for more info.

I recommend adding another effect that will set savedIds:

useEffect(() => {
  const idsArray = savedItems.map((item) => item.site_id)
  setSavedIds(idsArray) 
}, [savedItems]);
Janez Kuhar
  • 3,705
  • 4
  • 22
  • 45