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();
}, []);