Reputation: 41
I am working on a project , i must login after that send user to dashboard page where I have to pass data from one page to another i have error. i can see data with React developers tools but when i try to show i i have error "TypeError: Cannot read property 'state' of undefined"
---login--
handleLogin = () => {
axios.defaults.withCredentials = true;
let username = document.getElementById('username').value;
let password = document.getElementById('password').value;
const querystring = require('querystring');
axios.post('url', querystring.stringify({
username: username, //gave the values directly for testing
password: password,
}))
.then((res) => {
console.log(res)
if (res.data.hasError === false) {
let user = res.data.result.name;
this.props.history.push({
pathname: "/",
state:{
key:user
}
})
}
}).catch((error) => {
})
};
---Header---
class UserHeader extends Component {
render() {
return (
<span>
{this.props.location.state.key}
</span>
);
}
}
export default UserHeader;
---index.js-----
const app = (
<BrowserRouter>
<Switch>
<Route path="/login" component={Login}/>
<Route path="/" component={App}/>
</Switch>
</BrowserRouter>
)
ReactDOM.render(app, document.getElementById('root'));
TypeError: Cannot read property 'state' of undefined
in Header page
Upvotes: 1
Views: 97
Reputation: 109
You can use the history methods outside of your components. First, npm install history and create a history.js
import { createBrowserHistory } from 'history';
export default createBrowserHistory();
in header.js import history.js and use
<span>{history.location.state.key}</span>
Upvotes: 1
Reputation: 1075
Seems like you are trying to get state from regular props, but you should get them from route props. Here is an example of how it works in my project:
<Switch>
<Route path="/" exact render={(routeProps) => ( <BooksWrapper books={this.props.books} /> )} />
<Route path="/edit-book" render={(routeProps) => (
<EditBook bookInfo={routeProps.location.state.bookInfo} />
)} />
</Switch>
And then I get them like regular props.
Upvotes: 1