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.
The problem was in async requests inside the 'for' loop, to fix it the 'handleChange()' function was updated to this one
Thanks @hussain @derek