History does not work

Asked

Viewed 155 times

0

Guys my big problem there is the following, I other application I used the "history" property to redirect to another page, I learned that I didn’t need to matter anything from any lib to use history just was to disrupt it into function and use. But when atentificação passes it arrives at the line of "history" and of that error : "Unhandled Rejection (Typeerror): Cannot read Property 'push' of Undefined". as if history doesn’t have that function , I don’t really know how to proceed, because it’s the only way I know how to call another page by passing id and other data.

<script 
import React,{useState} from 'react';
import {  LoginMenu, ContainerImg, Formulario, Inputs, Realysub,ContainerLogin } from './styles';
import { GoPerson } from 'react-icons/go';
import { FaLock } from 'react-icons/fa';
import {Link} from 'react-router-dom'
import api from '../../services/api'


export default function LoginCard({history}) {
  const [email,setEmail] = useState('digite seu email')
  const[password,setPassword] = useState('digite seu password')
  
  
  async function handleSubmit(e){
      e.preventDefault();
      try {
       response = await api.post('/autentication',{email,password})
      } catch (error) {
        return console.log("error",error)
      }
      const {_id} = response.data
      history.push(`/areadoaluno/${_id}`)
  }
  
  

  • 1

    https://stackoverflow.com/q/42701129/4928642

1 answer

1


"History" exists as a props for components that were informed when creating a route. If for example you have a "/Register" route that is linked to a component with the same name, using it would look like this:

class Register extends React.Component {
  handleSubmit = (user) => {
    saveUser(user).then(() =>
      this.props.history.push('/dashboard')
    ))
  }
}

However, this props is not passed by default to the child components. For your "Logincard" to work the way you programmed it, you would have to pass the parent component props. The call on the parent component would look like this:

<LoginCard history={this.props.history} />

And your Logincard would look like this:

export default function LoginCard(props) {
  const [email,setEmail] = useState('digite seu email')
  const[password,setPassword] = useState('digite seu password')


  async function handleSubmit(e){
      e.preventDefault();
      try {
       response = await api.post('/autentication',{email,password})
      } catch (error) {
        return console.log("error",error)
      }
      const {_id} = response.data
      props.history.push(`/areadoaluno/${_id}`)
  }
}

Here is a tutorial explaining in more detail the process and another way to do it:

https://tylermcginnis.com/react-router-programmatically-navigate/

Browser other questions tagged

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