67588

Warning: Can't call setState (or forceUpdate) on an unmounted component

getting this warning everytime i sign in,

Warning: Can't call setState (or forceUpdate) on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method.

here my code

authpage.js

handleLoginSubmit = (e) => { e.preventDefault() let { email,password } = this.state const data = { email : email, password : password } fetch('http://localhost:3001/auth/login',{ method : 'post', body : JSON.stringify(data), headers : { "Content-Type":"application/json" } }).then(res => res.json()) .then(data => { if(data.success){ sessionStorage.setItem('userid',data.user.id) sessionStorage.setItem('email',data.user.email) } this.setState({loginData : data, userData : data, email:"", password:""}) if(data.token) { Auth.authenticateUser(data.token) this.props.history.push('/dashboard') } this.handleLoginMessage() this.isUserAuthenticated() }) } export default withRouter(AuthPage)

use withRouter so i can access props which i use to navigate this.props.history.push('/dashboard') if i didnt use withRouter i cannot access this.props

index.js

const PrivateRoute = ({ component : Component, ...rest }) => { return ( <Route {...rest} render = { props => ( Auth.isUserAuthenticated() ? ( <Component {...props} {...rest} /> ) : ( <Redirect to = {{ pathname: '/', state: { from: props.location } }}/> ) )}/> ) } const PropsRoute = ({ component : Component, ...rest }) => ( <Route {...rest} render = { props => ( <Component {...props} {...rest} /> )}/> ) const Root = () => ( <BrowserRouter> <Switch> <PropsRoute exact path = "/" component = { AuthPage } /> <PrivateRoute path = "/dashboard" component = { DashboardPage } /> <Route path = "/logout" component = { LogoutFunction } /> <Route component = { () => <h1> Page Not Found </h1> } /> </Switch> </BrowserRouter> )

i think the problem is with my withRouter, how can we access this.props without using withRouter ?

Answer1:

It's async so

this.setState({ loginData : data, userData : data, email:"", password:"" })

make error You can use <strong>this._mount</strong> to check component is mounted or unmount

componentDidMount () { this._mounted = true } componentWillUnmount () { this._mounted = false } ... if(this._mounted) { this.setState({ loginData : data, userData : data, email:"", password:"" }) ...

Answer2:

I had some problems using this.setState({ any }).

Every time the component was built, it called a function that used Axios and the response made a this.setState({ any }).

My problem was solved as follows:

In the componentDidMount() function I call another function called initialize() that I left as <strong>async</strong> and through it I can call my function that performs fetch and this.setState({ any }).

componentDidMount() { this.initialize(); } myFunction = async () => { const { data: any } = await AnyApi.fetchAny(); this.setState({ any }); } initialize = async () => { await this.myFunction(); }

Recommend

  • toString() for each element of an array in Javascript [duplicate]
  • JavaScript - Can we set javascript objects in cookies?
  • Function insertMany() unordered: proper way to get both the errors and the result?
  • Unzip archive in .Net CORE 1.0
  • Telegram bot API - Inline bot getting Error 400 while trying to answer inline query
  • Select value from xtype selection type checkbox CQ5
  • Ruby on Rails App deployed to heroku showing “We're sorry, but something went wrong”
  • Julia: How to give multiple workers access to functions that are 'include(…)' into a modul
  • Javascript CORS - No 'Access-Control-Allow-Origin' header is present
  • Exception creating JSON with LINQ
  • How to convert SOAP response with xsi values to json in WSO2esb
  • JPA flush vs commit
  • Angular2 Response for preflight is invalid (redirect) from some GET requests
  • saving file generated by TCPDF
  • Alternative To body {overflow:scroll;} That Will Prevent Page Jostling/Wriggling?
  • chrome.tabs.executeScript only fires when the Developer Console is open
  • Content-Length header not returned from Pylons response
  • Play WS (2.2.1): post/put large request
  • Different response to non-authenticated users and AJAX calls
  • Align navbar back button on right side
  • DotNetZip - Calculate final zip size before calling Save(stream)
  • How to apply VCL Styles to DLL-based forms in Inno Setup?
  • htaccess rewriting URLs with multiple forward slashes
  • bootstrap to use multiple ng-app
  • How to get icons for entities from eclipse?
  • Load html files in TinyMce
  • How can I get HTML syntax highlighting in my editor for CakePHP?
  • Free memory of cv::Mat loaded using FileStorage API
  • How do I configure my settings file to work with unit tests?
  • embed rChart in Markdown
  • Turn off referential integrity in Derby? is it possible?
  • IndexOutOfRangeException on multidimensional array despite using GetLength check
  • Is it possible to post an object from jquery to bottle.py?
  • Can't mass-assign protected attributes when import data from csv file
  • JaxB to read class hierarchy
  • How to get NHibernate ISession to cache entity not retrieved by primary key
  • Binding checkboxes to object values in AngularJs
  • How to Embed XSL into XML
  • How can I use `wmic` in a Windows PE script?
  • Unable to use reactive element in my shiny app