Filip Sikora
Filip Sikora

Reputation: 61

React - change route from function

My fetch function is sometimes returning errors. If that happens I would like to go to something like url/notfound and render NotFound component. Can it be done with react router? Are there any other ways to change route from function ?

Upvotes: 0

Views: 262

Answers (1)

Anandhu
Anandhu

Reputation: 827

You can show something like this
I am showing ES6 example

Let's assume that you have a state variable which updates loadError on fetch operations result

this.state={
   loadError:false
}

Like,

fetch(this.host+this.url,{method:"GET",redirect:"follow"}).then(()=>
     this.setState({loadError:true})      
)

somewhere in render() method

{loadError ? <Redirect to="/NotFound"/>}

Upvotes: 1

Related Questions