Inside the "for" loop "getKeys" function should create POST request and in the response it should update "encryptedKeys" state. But the state in slice is overwriting with new values and the old one is disappearing from the state.
function DragDrop() {
const dispatch = useDispatch();
const files = useSelector((state) => {
return state.file.uplaodedFiles;
});
const encryptedKeys = useSelector((state) => {
return state.file.encryptedKeys;
});
const [createEncryptionKey, results] = useCreateEncryptionKeyMutation();
const getKeys = async () => {
try {
const data = await createEncryptionKey(data).unwrap();
if (data) {
dispatch(setEncryptedKeys([...encryptedKeys, data]));
}
} catch (err) {
console.log(err);
}
};
const handleChange = (file) => {
let arr = [];
for (let i = 0; i < file.length; i++) {
getKeys();
const data = {
file: file[i],
};
arr.push(data);
}
dispatch(setUplaodedFiles([...files, ...arr]));
};
API
const api = createApi({
reducerPath: "file",
baseQuery: fetchBaseQuery({
baseUrl: "https://...",
}),
endpoints(builder) {
return {
createEncryptionKey: builder.mutation({
query: (data) => {
return {
method: "POST",
url: "/key",
body: {
key: data.key,
},
};
},
}),
};
},
});
If I upload 3 files, only one will be in "encryptedKeys" state but acctually 3 files should be there.
2
Answers
The problem was in async requests inside the 'for' loop, to fix it the 'handleChange()' function was updated to this one
Thanks @hussain @derek
It looks like you’re encountering an issue where only one encrypted key is being stored in the ‘encryptedKeys’ state when you expect all three files to be there. The problem stems from the asynchronous nature of the getKeys function inside your loop. Since getKeys is an asynchronous function, by the time the response is received and dispatch is called to update the state, the loop has already continued to the next iteration. This results in only one key being added to the state.