React/Redux - Function connection

Asked

Viewed 50 times

1

Hello!

I have a file containing a single function, it should return a boleano from a condition using the data from the Redux Storage. I can connect the file without being a Reactcomponent to Redux?

The function is responsible for authenticating the application. Therefore:

import { connect } from "react-redux";

const isAuthenticated = ({ user }) => {
  console.log("auth.js", user);
  return true;
}

const mapStateToProps = (state) => ({
  user: state.user,
});

export default connect(mapStateToProps, null)(isAuthenticated);

In the route file I try to call this function isAuthenticated():

import React from "react";
import { BrowserRouter, Switch, Route, Redirect } from "react-router-dom";
import { connect } from "react-redux";
import isAuthenticated from "./utils/auth";

const PrivateRoute = ({ component: Component, ...rest }) => {
    if (isAuthenticated()) return <Route component={Component} {...rest} />;
    else
        return (
           <Redirect
           to={`/login?redirect=${window.location.pathname}`}
           {...rest}
           />
        );
};

const AnonymousRoute = ({ component: Component, ...rest }) => {
  if (!isAuthenticated()) return <Route component={Component} {...rest} />;
  else return <Redirect to={`/app`} {...rest} />;
};

return (
    <BrowserRouter>
      <Switch>
        ...ROTAS
      </Switch>
    </BrowserRouter>
);

export default connect(mapStateToProps)(Routes);

However I get the following error: Erro javascript

Ps.: I am beginner in the world React JS. Thank you!

1 answer

1

You are doing it wrong. You should create a Hooks for this since you are using the functional React.

First, you should create a Hooks for the purpose of making a Rest request, because to check whether the user is valid or not, you would have to see this on the server side.

Here I used javascript’s own fetch but you can use Next if you want.

Hooks/fetch.js

const useFetch = (url, options) => {
  const [response, setResponse] = React.useState(null);
  useEffect(async () => {
      const res = await fetch(url, options);
      const json = await res.json();
      setResponse(json);
  },[]);
  return response;
};
export default useFetch

After we create the Hooks that checks the authentication, this Hooks will prompt useFetch to search the server for the answer.

*Hooks/auth.js

import useFecth from "./hooks/fetch";
const useAuthenticate = () => {
  const { data, loading, error } = useFetch("ENDERECO_API");
  const [isAuth, setAuth] = useState(false);
  useEffect(() => {
    setAuth(!loading && !error);
  }, [data]);

  return isAuth;
};

Now just call this Hooks where you want to check whether the user is validated or not, in your example, would look more or less like this:

const PrivateRoute = ({ component: Component, ...rest }) => {
  const isAuth = useAuth();
  isAuth ? (
    <Route component={Component} {...rest} />
  ) : (
    <Redirect to={`/login?redirect=${window.location.pathname}`} {...rest} />
  );
};

I used a if ternary to check, but can be basic if same.

I took the HOC because this is no longer necessary in this concept since the Hooks came with this purpose already.

I hope this will suit you or give you at least a better idea of how to find a better solution.

  • Hello, thanks in advance for the contribution. Referring to the quotation regarding the server check, this is exactly what I would like to do. My token data is persisted in localStorage, and I need to recover it using React-Redux. For this reason I need to make the connection.

Browser other questions tagged

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