Am I using useState incorrectly here?

For context I am attempting to to set up multipart uploads to S3, and yes I did see https://github.com/nramkissoon/t3-s3 and my code is based on that. I have these two useState:
const [uploadId, setUploadId] = useState<string[]>([]);
const [partPresignedUrls, setPartPresignedUrls] = useState<{ [partNumber: number]: File }[]>(
[]
);
const [uploadId, setUploadId] = useState<string[]>([]);
const [partPresignedUrls, setPartPresignedUrls] = useState<{ [partNumber: number]: File }[]>(
[]
);
These states get updated based on a trpc call:
fetchPresignedUrls({ fileName: file.name, filePartTotal: Object.keys(parts).length })
.then((res) => {
const urls = res.urls.map((data) => ({
url: data.url,
partNumber: data.partNumber,
}));
console.log("FE has now received the following urls: ", urls)
console.log("FE has now received the following uploadId: ", res.uploadId)
setPresignedUrl([...presignedUrl, urls]);
setUploadId([...uploadId, res.uploadId]);
})
.catch((err) => console.log(err));
}
fetchPresignedUrls({ fileName: file.name, filePartTotal: Object.keys(parts).length })
.then((res) => {
const urls = res.urls.map((data) => ({
url: data.url,
partNumber: data.partNumber,
}));
console.log("FE has now received the following urls: ", urls)
console.log("FE has now received the following uploadId: ", res.uploadId)
setPresignedUrl([...presignedUrl, urls]);
setUploadId([...uploadId, res.uploadId]);
})
.catch((err) => console.log(err));
}
But the useState only saves the data for the last file. From the console.log I know that I do receive the urls and the uploadId, for both the client and server.
GitHub
GitHub - nramkissoon/t3-s3: Example create-t3-app with AWS S3 presi...
Example create-t3-app with AWS S3 presigned URL integration - GitHub - nramkissoon/t3-s3: Example create-t3-app with AWS S3 presigned URL integration
3 Replies
Mordi
Mordi2y ago
console.logs
scinorandex
scinorandex2y ago
You want to use a callback inside the setState the variable that the setState function is mapped to only updates when it's rerendered setPresignedUrl((e) => [...e, urls]); setUploadId((e) => [...e, res.uploadId]); the variable passed by react into the callback function is always up to date @Mordi hope this helps
Mordi
Mordi2y ago
It did! Thanks!
Want results from more Discord servers?
Add your server