How to create a React component that receives a query string and then make a request?

Asked

Viewed 35 times

0

Hello, I’m having a hard time getting a page on React to work. This page receives a query string with token and email, where I should pick them up and make a request for the account to be validated, in case making a request and receiving the return of the file and display the message, in which case a modal.

useEffect(() => {
    dispath(setLoadingShow());
    const email = query.get('email') as string;
    const token = query.get('token') as string;
    const encondedToken = encodeURIComponent(token);
    if (!encondedToken && !email) {
      history.push('/');
    } else {
      fetchResetPassword(email, encondedToken)
        .then(() => {
          setErrorIcon(<RiCheckDoubleFill className={global.iconSuccess} />);
          setTitle('Sua senha foi alterada, favor verificar seu e-mail');
          onDialog();
        })
        .finally(() => dispath(setLoadingHide()));
    }
  }, [query, global, history, dispath]);

My point is that by accessing the component, it starts making thousands of requests non-stop, I don’t know where I could be wrong. As long as the page continues, he will make requests over and over.

2 answers

1

Hello! I think your problem is keeping "Dispatch" in the dependency array. Useeffect causes any of the variables stored within that array to be "heard", and any changes to it, it executes useEffect again.

useEffect(() => {
    dispath(setLoadingShow());
    const email = query.get('email') as string;
    const token = query.get('token') as string;
    const encondedToken = encodeURIComponent(token);
    if (!encondedToken && !email) {
      history.push('/');
    } else {
      fetchResetPassword(email, encondedToken)
        .then(() => {
          setErrorIcon(<RiCheckDoubleFill className={global.iconSuccess} />);
          setTitle('Sua senha foi alterada, favor verificar seu e-mail');
          onDialog();
        })
        .finally(() => dispath(setLoadingHide()));
    }
  }, [query]);

I would keep only the query to avoid redundancies.

0

Be careful with the Eslint auto formatting your code, in these critical fields state you put when necessary the Eslint disabled tag:

useEffect(() => {
  dispath(setLoadingShow());
  const email = query.get('email') as string;
  const token = query.get('token') as string;
  const encondedToken = encodeURIComponent(token);
  if (!encondedToken && !email) {
    history.push('/');
  } else {
    fetchResetPassword(email, encondedToken)
    .then(() => {
      setErrorIcon(<RiCheckDoubleFill className={global.iconSuccess} />);
      setTitle('Sua senha foi alterada, favor verificar seu e-mail');
      onDialog();
    })
    .finally(() => dispath(setLoadingHide()));
  }
// eslint-disable-next-line
}, [query]);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.