skip to Main Content

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


  1. Chosen as BEST ANSWER

    The problem was in async requests inside the 'for' loop, to fix it the 'handleChange()' function was updated to this one

      const handleChange = (file) => {
        document.querySelector(".error").innerHTML = "";
        let arr = [];
        for (let i = 0; i < file.length; i++) {
          const { publicKeyPEM, privateKeyPEM } = createKeys();
          createEncryptionKey({
            token,
            key: publicKeyPEM,
          })
            .unwrap()
            .then((res) => {
              const keys = decryptKeys(res, privateKeyPEM);
              const data = {
                file: file[i],
                forge: keys,
              };
              arr.push(data);
              dispatch(setUplaodedFiles([...files, ...arr]));
            })
            .catch((err) => console.log(err));
        }
      };

    Thanks @hussain @derek


  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search