Search code examples
javascriptreactjsreduxredux-toolkit

Changing redux state asynchronously


I use redux toolkit and I have my initial state like this:

initialState: {
  details: {
    id: "",
    base64: "",
  },
},

I want to fetch an image base64 inside of my initial state, whenever user logged in. I decided to do such thing in my axios:

axios.post(`${process.env.REACT_APP_API_URL_API_LOGIN}`, {
  softWareOrUser: false,
  userName: userName,
  password: password,
})
  .then((r) => {
    if (r.data.resCode === 1) {
      dispatch(setDetails({ ...details, id: r.data.Data.Id.toString() }));
      ImageFetchingHandler(r.data);
    }
  })
  .then((d) => {
    navigate({ pathname: "/main" });
  })
  .catch(() => {
    alert("user name or password is incorrect");
  });

This is how I fetch image base64:

const { details } = useSelector((state) => state.axiosdetails);
const ImageFetchingHandler = ({ token }) => {
  axios({
    method: "post",
    url: `${process.env.REACT_APP_API_URL_API_FETCH_IMAGE}`,
    headers: {
      Authorization: `Bearer ${token}`,
      "Content-Type": "application/json",
      "DotNet-Timeout": 30000,
    },
    data: JSON.stringify({
      id: details.id,
    }),
  })
    .then((d) => {
      Cookies.set("userImage", JSON.stringify(d.data), {
        path: "/",
        expires: 3,
        sameSite: "strict",
        secure: window.top.location.protocol === "https:",
      });
    });
};

I have a problem, the ImageFetchingHandler sends id value as an empty string even though redux developer tools shows the actual id value.

Redux developer tools shot

What is the problem?

Is there any way to solve it?


Solution

  • It would seem that the r.data object has already all the details you need, specifically that it has the r.data.Data.Id property that you are setting the id state to that you are later immediately attempting to access in the ImageFetchingHandler function.

    dispatch(setDetails({ ...details, id: r.data.Data.Id.toString() }));
    ImageFetchingHandler(r.data); // <-- id is in the data
    

    In addition to accessing data.token in ImageFetchingHandler you can also access data.Data.Id for the id value for the payload.

    const ImageFetchingHandler = ({ Data: { Id: id }, token }) => {
      axios({
        method: "post",
        url: `${process.env.REACT_APP_API_URL_API_FETCH_IMAGE}`,
        headers: {
          Authorization: `Bearer ${token}`,
          "Content-Type": "application/json",
          "DotNet-Timeout": 30000,
        },
        data: JSON.stringify({ id }),
      })
        .then((d) => {
          Cookies.set("userImage", JSON.stringify(d.data), {
            path: "/",
            expires: 3,
            sameSite: "strict",
            secure: window.top.location.protocol === "https:",
          });
        });
    };