user12465675
user12465675

Reputation:

Reactjs push route after dispatch

Hello I am having trouble finding where I can call a route with push after authenticating the user

I did it using redux

my action:

const AuthenticateUser = (login, password) => {
    return dispatch => {
        dispatch (startAuth ());
        // fetching data
        api.post ('/ login', {login, password})
            .then (response => {
            localStorage.setItem ('token', response.data [0]);
            dispatch (userAuthenticated (response.data [1]))
        })
            .catch (err => {console.error (err);});
    }
}

export default AuthenticateUser;

my reducer:

const authReducer = (state = initialState, action) => {
    switch (action.type) {
        case USER_AUTHENTICATED:
            return {
                ... state,
                loading: false,
                authenticated: true,
                user: action.user,
            }
        case USER_FAILED_AUTH:
            return {
                ... state,
                loading: false,
                message: action.error

            }
        default:
        return state;
    }
}

and my form

const SignIn = (props) => {
  const classes = useStyles();
  const dispatch = useDispatch();
  const [login, setLogin] = useState('');
  const [password, setPassword] = useState('');
  const handleSubmit = (e) => {
    e.preventDefault()
    dispatch(auth(login, password))
  }
  return (
    <div className={classes.root}>

      <Grid container spacing={2} className={classes.gridMain}>

        <Grid item lg={12} md={12} sm={12} xs={12} align="center">
          <img src={require("../nodejs-icon.svg")} alt="bug" height={100} />
        </Grid>

        <Grid item lg={12} md={12} sm={12} xs={12} className={classes.TextField}>
          <form onSubmit={handleSubmit}>
            <TextField
              className={classes.input2}
              id="demo2"
              label="Usuário"
              variant="outlined"
              value={login}
              onChange={(e) => setLogin(e.target.value)}
              InputLabelProps={{
                classes: {
                  root: classes.label,
                  focused: classes.focusedLabel,
                  error: classes.erroredLabel
                }
              }}
              InputProps={{
                classes: {
                  root: classes.cssOutlinedInput,
                  focused: classes.cssFocused,
                  notchedOutline: classes.notchedOutline,
                },
                startAdornment: (
                  <InputAdornment position="start">
                    <PersonSharpIcon style={{ fontSize: 25, color: 'rgba(20, 176, 12,0.9)' }} />
                  </InputAdornment>
                )
              }}
            />
            <TextField
              className={classes.txtFd}
              id="demo2"
              label="Senha"
              variant="outlined"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              InputLabelProps={{
                classes: {
                  root: classes.label,
                  focused: classes.focusedLabel,
                  error: classes.erroredLabel
                }
              }}
              InputProps={{
                classes: {
                  root: classes.cssOutlinedInput,
                  focused: classes.cssFocused,
                  notchedOutline: classes.notchedOutline,
                },
                startAdornment: (
                  <InputAdornment position="start">
                    <LockSharpIcon style={{ fontSize: 25, color: 'rgba(20, 176, 12,0.9)' }} />
                  </InputAdornment>
                )
              }}
            />
            <ButtonBase variant="raised" disableFocusRipple="false" disableRipple="false" centerRipple="false">
              <Typography noWrap className={classes.labelForgot} variant="subtitle2">
                Esqueci minha senha
          </Typography>
            </ButtonBase>
            <Button type="submit" className={classes.button} variant="raised" disableFocusRipple="false" disableRipple="false" centerRipple="false">
              Entrar
        </Button>
          </form>
        </Grid>

I have a route and after I authenticate this user I wanted to send it to a route or display an error msg, but I don't know where in the code to do it and how I would get it.

my route

const AppRouter = () => (
  <BrowserRouter>
          <Route path="/xd" component={AuthPage} exact={true} /> 
          <Route path="/dashboard/addProduct" component={AddProduct} exact={true} /> 

  </BrowserRouter>
);

Upvotes: 0

Views: 261

Answers (2)

sardok
sardok

Reputation: 1116

You may use useEffect in SignIn component, which checks for flag authenticated: true (where this variable is passed via props) and does the redirection.

Something like that

  useEffect(() => {
    const { authenticated, navigation } = props;
    if (authenticated) {
        navigation.navigate(Routes.GoodPlace);
    }

  });

Upvotes: 0

jean182
jean182

Reputation: 3505

So this is in order to give you an answer that is readable instead of using the comments. In your SignIn component:

import { withRouter } from "react-router-dom";
const SignIn = (props) => {
 const { history } = props;
 const { push } = history;
 // more variables
 const handleSubmit = (e) => {
  e.preventDefault()
  // You pass the push function over here.
  dispatch(auth(login, password, push))
 }
// Rest of the logic
}
export default withRouter(SignIn);

The withRouter would give you all the props that are coming from react-router, this will allow you to use the history object, which contains the push function, to redirect the user to the page you want.

Then in your authenticate function which I'm guessing is the ´AuthenticateUser´ function you could do this:

const AuthenticateUser = (login, password, push) => {
return dispatch => {
    dispatch (startAuth ());
    // fetching data
    api.post ('/ login', {login, password})
        .then (response => {
        localStorage.setItem ('token', response.data [0]);
        dispatch (userAuthenticated (response.data [1]))
        // push goes here
        push("/your-awesome-route")
    })
        .catch (err => {console.error (err);});
}
}

export default AuthenticateUser;

Upvotes: 1

Related Questions