1

I'm building a React app and I would like to know how I can redirect to a 404 page if when in the onMount method of the component. I don't find any data coming from the api

I have already build the 404 page and route

<Route path="*" element={<NotFoundView />} />

Code:

  const getExercice = async () => {
    try {
      const response = await http.get(`/exercicePost/${id}`);
      if (response.status !== 400) {
        setExercice(response);
      }
    } catch {}
  };

  useEffect(() => {
    if (id !== undefined) {
      setTitle(id.replaceAll("-", " "));
      setTitleSplit(id.split("-"));
    }
    getExercice();
  }, [""]);

  if (exercice !== undefined) {
    return (
      <div className="main-container single-exercice">
        <div className="single-exercice-go-back grid grid-cols-3 ">
          <ButtonGoBack text="retour" link="../" />
        </div>
        <div className=" md:grid  md:grid-cols-3 gap-4">
          <div className="single-exercice-title">
            <span className="single-exercice-title-transparent">Exercice</span>
            {titlesplit.map((element: string, id: number) => (
              <span className="single-exercice-title-full" key={id}>
                {element}
              </span>
            ))}
          </div>

          <ImageWrapper imgUrl="d" alt="d" />
        </div>
        <div className="single-exercice-description">
          <PartFrame title="Description" />
          <p>{exercice.description}</p>
        </div>

        <div className="single-exercice-how-to">
          <PartFrame title={"Comment faire le " + title} />
          <TextList list={exercice.howToRealise} />
        </div>
      </div>
    );
  } else {
    return <h1>Wrong name</h1>;
  }
};

I would like to instead of returning <h1>Wrong name</h1> redirect the user to the path "*" and not mount the page.

1
  • what do you mean by data is not coming ? by an error or how ? Commented Oct 4, 2022 at 11:30

1 Answer 1

3

solution 1 : change :

else {
    return <h1>Wrong name</h1>;
  }

to :

else {
    return <NotFoundView />;
  }

do not forget to import import NotFoundView from "<path>/NotFoundView ";

Solution 2 :

use the useNavigate hook in your case :

import { useNavigate } from "react-router-dom";
function Test () {
  const navigate = useNavigate();  
  if (.......) {
    return ...........;
  } else {
    return navigate("*");
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

thank you it was so simple I don't know why I didn't think of it
it happens if it didn't work the way you want think of another one

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.