0

so i was using redirect in react-router-dom, i have 2 pages, home and create when the form in create is done and has been submitted, it will execute the <Redirect> function, and it works, but the ComponentDidMount was not being fired again, i need to reload the page to make the ComponentDidMount to make it start again, here is my code

this is how i redirect in the Create file :

if(this.state.createNew){
        return <Redirect to='/home'/>
    }

and this is my ComponentDidMount in my Home file :

componentDidMount() {
    console.log("hi")
    }

the console print hi only on the initial render, when i redirect back to the page it does not fire again, i tried use setState inside the ComponentDidMount but it still not being re rendered.

when i tried using Link to method, it works, the ComponentDidMount is being fired again, but Link to is not what i want, because it does not automatically redirect like the <Redirect> do

i got an error when i try to use the useHistory function :

React Hook "useHistory" is called in function "simpan" which is neither a React function component or a custom React Hook function  react-hooks/rules-of-hooks

here is how i use my useHistory :

function simpan(event){
    event.preventDefault()
    const email = event.target.elements.email.value
    const name = event.target.elements.name.value
    const admin = event.target.elements.admin.value
    const active = event.target.elements.active.value
    const history = useHistory()
    console.log(email)
    history.push('/home')
}

thanks before, anyhelp will be appriciated

Walls
  • 149
  • 13

2 Answers2

1

instead of <Redirect /> why don't you use history.push('/home'). this will take you to the new route once state is true and call componentDidMount

how to use history:

import { useHistory } from 'react-router-dom'

then inside your component: const history = useHistory()

then whether you need to change the route:

history.push('/home')

Red Baron
  • 7,181
  • 10
  • 39
  • 86
0

If your create is class component just use this.props.history.push("/home") instead of <Redirect> tag. As create component is your route it will automatically get history object in props. why to use history instead of redirect tag in your case

Simple example of programatic navigation with react routing Please check console of browser while checking this example