How to run code 'after' state is populated?

I’m using libraries.source.api.get() combined with libraries.source.populate() to get specific CPT into state

However, running code ‘after’ the populate response is resolved occurs before the data is actually in the state (i get errors trying to access state.source.downloads[id] because it happens while the data is not there)

Is there a clean way to run code after state has been populated ?
Im currently working around the issue with a setTimeout but this isnt ideal…

  const [files, setFiles] = useState();
  const filesID = [...content.documents].map((item) => item.ID);
  const filesIDstring = filesID.join();

  useEffect(() => {
    //   async inside useEffect
    const fetchData = async () => {
      // get the data from the api
      const response = await libraries.source.api.get({
        endpoint: "downloads",
        params: { _embed: true, include: filesIDstring },
      });
      await libraries.source.populate({ response, state }).then(
        setTimeout(() => {
          setFiles(filesID.map((id) => state.source.downloads[id]));
        }, 100)
      );
    };
    // call the function
    fetchData();
  }, []);

Fixed by doing the following

useEffect(() => {
    //   async inside useEffect
    const fetchData = async () => {
      // get the data from the api
      const response = await libraries.source.api.get({
        endpoint: "downloads",
        params: { _embed: true, include: filesIDstring },
      });
      const pop = await libraries.source.populate({ response, state });
      setFiles(pop.map(({ id }) => state.source.downloads[id]));
    };
    // call the function
    fetchData();
  }, []);

i believed populate returned a response but it doesnt, it returns an array
so using the array directly works without causing errors :slight_smile:

my bad, need to pay more attention when reading the api reference haha