I see the flavours of this question have been asked previously, but I don't appear to be able to use the answers to generate the effect I'm seeking. Completely accept that I might be missing the point somewhere...feel free to redirect me elsewhere if this is a well-understood/accepted situation.
Anyway, I'm using state to store an array of values, which needs to be updated via one or more API calls on a given action. As a precursor to calling the API, I want to reset the array to be empty, but aren't able to do it in the way I'd anticipated. Grateful for any explanation/suggestion/pointers.
The following pseudocode hopefully demonstrates what I'm trying to do, which is, when retrieveAllPreviousManuscripts is called it should:
- clear any previously loaded items
- call getManuscripts 'n' times and repopulate the piece of state
const [manuscriptsForReview, setManuscriptsForReview] = useState([]);
const getManuscripts = (offset, limit) => {
setLoadingInProgress(true);
let newManuscripts = [];
doFetch(
`${someAPI()}?offset=${offset}&limit=${limit}`,
)
.then((response) => parseResponseObject(response, addError, false))
.then(handleErrorResponses)
.then((data) => {
newManuscripts = data.crowdsourcedManuscripts;
setManuscriptsForReview([...manuscriptsForReview, ...newManuscripts]);
})
.catch((e) => {
//someErrorHandling
})
.finally(() => {
setLoadingInProgress(false)
});
};
const retrieveAllPreviousManuscripts = async () => {
setManuscriptsForReview([]);
// manuscriptsForReview.length = 0;
let offset = 0;
do {
// eslint-disable-next-line no-await-in-loop
await getManuscripts(offset, numberToRetrievePerCall);
offset += defaultPageSize;
} while (offset < originalPageSize);
};
What I'm not understanding is why setManuscriptsForReview([]); is not having any effect when called from retrieveAllPreviousManuscripts.
If I replace it with manuscriptsForReview.length = 0; then everything works, but
- This feels like a hack!
- I'm reluctant to do it without understanding why the initial method doesn't work.