so this is my app.js
import React from 'react'
import {Header} from './common/header.component';
import {View} from './components/main';
export const {Provider, Consumer} = React.createContext('hello');
export class App extends React.Component {
constructor(props) {
super(props);
this.state = {
auth: 'hello'
};
this.authState = this.authState.bind(this);
}
authState(value){
console.log(value);
if(!value){
return this.state.auth;
} else if(typeof value === 'object'){
this.setState(value);
}
}
render() {
return (
<div className="app">
<Header/>
<Provider value={this.state.auth}>
<View updateAuth={this.authState}/>
</Provider>
</div>
)
}
}
and this is my signin component
import {Consumer} from '../main.js';
export class Signin extends React.Component {
constructor(props) {
super(props)
this.state = {
userUsername: '',
userPassword: ''
};
console.log(this.props);
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(e) {
this.setState({
[e.target.name]: e.target.value
})
}
handleSubmit(e) {
e.preventDefault();
return signinApi({userUsername: this.state.userUsername, userPassword: this.state.userPassword}).then((data) => {
console.log(data);
this.props.updateAuth({
auth: data.data.data
});
this.props.history.push('/home')
}).catch((err)=>{
alert(err.message)
})
}
render() {
return (
<Consumer>
{auth => auth ? (<Redirect to='/'/>) : (
<div>
<form onSubmit={this.handleSubmit}>
<input type="text" value={this.state.userUsername} name="userUsername"
onChange={this.handleChange}/>
<input type="password" value={this.state.userPassword} name="userPassword"
onChange={this.handleChange}/>
<input type="submit"/>
</form>
<Link to="/signup">Signup</Link>
</div>
)}
</Consumer>
)
}
}
So, what I am trying to do here is maintain a global state of auth, to handle protected routes, and if already logged, I'd like to redirect to the home page.
But as soon as I load the signin component, React throws an error: Invalid type. I can't seem to figure out, what's the problem here.
Also, is my understanding of the context API correct?
EDIT: Including error stack
Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
Check the render method of `Signin`.
in Signin (created by Route)
in Route (created by View)
in Switch (created by View)
in View (created by App)
in div (created by App)
in App
in Router (created by BrowserRouter)
in BrowserRouter
vendor.js:1297:7
import {Consumer} from '../main.js'; console.log(Consumer);ProviderandConsumerwere still undefined. So instead I replaced it with a variable, and then used<Variable.Provider>and<Variable.Consumer>in the required places.