How to redirect to other page in react outside component in a function

Viewed 65

I am using a function to handle http responses in react. this function is outside of component in a separate file name httpErrorHandler.js

  export const redirectError = (command, message, type, path) => {
      if (command === "toast") {
        type(message, {
          position: toast.POSITION.TOP_RIGHT,
        });
      }
      if (command === "redirect") {
        return <Redirect push to="/laksjdsdlkjsdfkasjhfklsdjh" />;
      }
    };

i am calling this function when requesting to server

requestFile.js

export const getSomeApis = async () => {
  let data;
  await getApi(URL)
    .then((info) => {
      data = info;
      redirectError ("toast",info.status, "redirect", "Catched it successfully");
    })
    .catch((error) => {
      redirectError (
        "redirect
,        error.response.status,
        "redirect",
        error.response.data.errors[0].message
      );
    });
  if (data) {
    return data;
  }
};

I wanna redirect my page in redirectError function which dose not work. What is the best way for redirecting to another page out of component?

1 Answers

Just use windows.location.href instead of Redirect

if (command === "redirect") {
  windows.location.href="/laksjdsdlkjsdfkasjhfklsdjh";
}
Related