I am trying to implement facebook login for my react app (with redux).
The component "FacebookLogIn" in my loginUser.js file looks like this:
<FacebookLogin
appId="375026166397978"
autoLoad={true}
fields="name,email,picture"
onClick={this.componentClicked.bind(this)}
callback={this.responseFacebook} />
So when I try to import an action like this:
import { loginWithFaceBook } from '../actions/';
And try to login with facebook through the componentClicked function:
componentClicked(){
console.log(this.props);
this.props.loginWithFaceBook(facebookUser);
}
I got an error
bundle.js:51161 Uncaught TypeError: this.props.loginWithFaceBook is not a function
I think this is scope issue since I also import a normal login function from 'actions' folder as {login}, and this.props.login works as normal, but I don't know how to fix it.
I fixed the issue by removing this.props. So how would I make this function an asynchronous function, I tried chaining the then callbacks but it does not work ?
componentClicked(){
loginWithFaceBook(facebookUser).then(() => {
this.props.history.push('/posts');
}).catch((e) => {
alert(e);
});;
}
The error is:
bundle.js:51165 Uncaught TypeError: (0 , _actions.loginWithFaceBook)(...).then is not a function
I would really appreciate any help.
Change
this.props.loginWithFaceBook(facebookUser);
to
loginWithFaceBook(facebookUser);
As you are importing
import { loginWithFaceBook } from '../actions/';
you don't need to use this.props you can directly use it. this.props comes to picture when you want to use parent's props.
Related
Im really new to react and react-native and having problem with this really simple code below.
The code below is on a minimal react native app.
It renders the content inside the render method but looks dont executing the instructions inside the constructor, i havent the alert box neither the log appears in console.
I need ensure a variable is initialized just on application startup and it was my way to check it, im thinking about use a logic using Undefined and give up on using contructor.
Some related links i found:
constructor in React not being called upon component being instantiated
Console.Log Not Being Called Inside React Constructor
My code :
class TestComponent extends Component {
Constructor(props){
this.super(props);
console.log("CalingConstructorLog"); // do nothing
Alert.alert("CalingConstructorLog"); // do nothing
}
render() {
return (
<Text>It renders OK!</Text>
);
}
}
export default TestComponent;
React electron on windows, if A is null, call A.test will make the application stop working, then the user has to close the application and restart it.
How to let react ignore the error, and continue work. The code has many A.test, I can't write everywhere if(A) A.test.
If this can't be resolved, can I print the error on the web view? So I don't have to remote visit the user's computer to see the console error.
NOTE
I think the solution is to use react error boundaries, as suggested in the console.
You already pointed out that you're using error boundaries, so after testing your scenarios in this fiddle I believe your implementation might be incorrect.
Given a similar implementation for ErrorBoundary in the docs:
class ErrorBoundary extends React.Component {
state = { hasError: '' };
render() {
return this.state.hasError ? (
<span>Oops! Something went wrong:<br />{this.state.hasError}</span>
) : this.props.children;
}
}
ErrorBoundary.getDerivedStateFromError = (error) => ({ hasError: error.toString() });
This component will render the fallback when any of its children breaks.
Error boundaries are React components that catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI
It will look similar to:
<MyReactApp>
<ErrorBoundary>
<ChatContent />
</ErrorBoundary>
</MyReactApp>
Now any error in ChatContent will be catch by ErrorBoundary giving you the opportunity to render the fallback like:
Oops! Something went wrong:
ReferenceError: test is not defined
The code has many A.test, I can't write every where if(A) A.test
But why? You can use some editor for multi file editing.
So you can replace A.test() to safeTest(A) function.
export const safeTest = (Obj) => {
if (Obj) {
Obj.test();
} else {
// Any action you want
}
}
It is hard to offer an answer to your question because I don't see your project codes, but if your react version is 16 you can use a special component lifecycle method that name is componentDidCatch.
Inside this method you will have these values:
componentDidCatch(error, info) {
// Do something with error and info
}
Even you can use setState inside this method and show you want. I think this method can help you for your second desire, the printing error in web view.
I tend to favor using default props. You can set a value for the component to assign to a prop if the prop is passed in undefined. For example, if your component depends on an array nested within an object, you could set that value as an empty array by default. This is especially handy when your component depends on an array of results from an API call, but the component renders before the request finishes.
If you want to make the minimal effort to catch all the unhandled errors from both main and renderer processes within Electron as well as showing them to the user via a dialog, the easy way is to use electron-unhandled which does exactly that:
After having installed it (npm i electron-unhandled), in both your main and renderer entry files (likely their root index.js), you just have to add, at the beginning:
const unhandled = require('electron-unhandled');
unhandled({ showDialog: true });
Now, that being said, it's a good practice to use a global error catcher but it's a really bad one if you use only that. You should try covering your error handling more accurately, at least method by method:
.then() { ... }.catch(err => ...) for your promises,
(..., (err, res) => { if (err !== null) { ... } ... ) for your callbacks,
try { ... } catch(err) { ... } for non-async or await-based code code parts.
And, as a side-note, I myself created a dependenciless library to make it safe and easy to create a global errors dictionary in order to well-organize your errors but there are other alternatives if this one doesn't fit your needs.
I guess the best possible solution to this would be surrounding your A.test in try and catch. In this case what you can do is catch the error is A is null and perform some error page from your side incase you want it or just keep the error silent incase you dont want to perform any operation and suppress the error and continue execution.
You can also wrap A.test in a function with try-catch and use that function instead of A.test. In this way you can avoid multiple try-catch block and you can handle the error as per your requirement here.
I try to load the ID from a ble device via AsyncStorage that I save in a another component. But then I do this I get the following error:
ExceptionsManager.js:65 Cannot read property 'loadMac' of undefined
This is my loadMac() function:
export function loadMac() {
AsyncStorage.getItem(MAC_KEY)
.then((item) => {
console.log(item);
return item;
})
.catch((error) => {
console.log(error);
});
}
And I call this function in my component like this:
store.loadMac();
Then I try
AsyncStorage.getItem(MAC_KEY)
.then((item) => {
console.log(item)});
I will get my ID.. but not from my function that I have in another file.
Any solution ?
The error message says store is not defined, so you should look for a solution checking it.
By the code you posted I am assuming you've tried to have 2 different components: one stateless component named 'store' which you are exporting to access its' loadMac function. And another where you are importing the 'store' component. Correct me if I'm wrong.
If this is the case, your export syntax is incorrect. It should be something similar to this
export default const Store = () => {...}
And then import it like this:
import Store from './yourPathToStore';
If it's not, then you shouldn't have that export and also clarify what is exactly your 'store'.
Hope it helps.
First, some context.
I'm using Redux to manage authentication state of my app and have Auth as a Redux container (or smart component).
I've created a wrapper (a higher-order component) that takes Auth and returns it:
export default function AuthWrapper(WrappedComponent) {
class Auth extends Component {
... <Auth stuff here> ...
}
return connect(mapStateToProps, mapDispatchToProps)(Auth);
}
It seems to me that in order to use the wrapper, I just need to invoke it with a component I want to have behind my auth. For example, let's say I'm authenticating a component called UserPage with the wrapper, à la:
const AuthenticatedUserPage = AuthWappper(UserPage)
However, when I use the wrapper like this, React isn't happy with me. I get the following error:
Warning: AuthenticatedApp(...): A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.
My best guess is that it doesn't like the connect-ified component that Redux will create when I return it from AuthWrapper... which leads me to my question:
Does React support higher-order components when those components create Redux containers? And if so, why would React be throwing this error?
Here's my two cents. I think the error is occurring elsewhere.
According to this simplified version of the connect function in react-redux, the connect function is simply returning another react component. So in your case, you're returning a component, wrapped inside another component, which is still valid. A container is basically a component.
Read https://gist.github.com/gaearon/1d19088790e70ac32ea636c025ba424e for a better understanding of the connect function.
I also tried the following in my own application and it worked.
import Layout from '../components/Layout'
//Do some other imports and stuff
function wrapper(Layout) {
return connect(null, mapDispatchToProps)(Layout);
}
export default wrapper()
Like the error states, you might just simply be returning an invalid component somewhere in your app. Your app might be throwing the error because you're not wrapping a return call in parentheses on your render method.
I have a horizon/react app with react router and I have a simple button in my app:
<Link className="dark button" to="/">Another Search</Link>
When I click on it, I get the following exception:
Uncaught TypeError: Cannot read property 'getHostNode' of null
The error comes from:
getHostNode: function (internalInstance) {
return internalInstance.getHostNode();
},
Any idea why am I getting this?
I was facing a similar issue. It turns out that, in my case, was highlighthjs removing comments from the generated dom.
For text, React 15 is adding comment with the reactid instead of a span tag, as in:
<!-- react-text: 248-->
Another Search
<!--/react-test-->
Can you try something like this?
<Link className="dark button" to="/"><span>Another Search</span></Link>
This will force the generated DOM to include the span with the proper data-reactid attribute.
I would file an issue with react-router, maybe they can do that internally so you would not have to bother about it. But there are challenges with that as the Link child could be basically anything.
I have run into this issue multiple times in the last few days (new to react) and in almost all the cases, there was some syntax/code error that was not caught anywhere else. One example: If you write:
getInitialState() {
showModal: false
},
instead of:
getInitialState() {
return {
showModal: false
};
},
you will get this error. That is unless your build process does not already catch the error. Hope this helps someone (or myself in a couple of days. Hi Niyaz, you are welcome!).
If anyone else finds this thread. For me this turned out to be a null error for a prop.
Code generating error:
<Menu InventoryCount={this.state.inventoryModel.length} />
Working null checked code:
<Menu InventoryCount={this.state.inventoryModel ? this.state.inventoryModel.length : 0} />
For me, it's a typo which results in importing component from wrong module.
import { Link, Icon } from 'react-router';
import { Tag } from 'antd';
it should be
import { Link } from 'react-router';
import { Tag, Icon } from 'antd';
I just had to restart my nodemon backend.
Very interesting :) for me, it turned out that I was consuming props incorrectly in child component. Might be helpful for someone.
function Parent(){
const styleEle = { width: '100px'};
return (<div>
<Child styleO={styleEle}/>
</div>);
}
function Parent(props){
// here i was directly using <div style={styleO}> causing issue for me
return (<div style={props.styleO}>
{'Something'}
</div>)
}
if you getting error like "getHostNode" of null then its a error related to old code which is written before and it comes with version update of react
we have two ways to resolve the same
1) First we have to uninstall react from project and than again install react with the version specified( old one 15.4.2) current version of react is 15.6.1
2) Second way is bit time consuming but for future of application its good , go through the old code and handle errors(error handling of promises ) with the correct way following are few links which help you to figure out whats running behind
https://github.com/facebook/react/issues/8579
https://github.com/mitodl/micromasters/pull/3022
I got this error trying to render undefined value by mistake.
render(){
let name = this.getName(); // this returns `undefined`
return <div>name: {name}</div>
}
The fix is to fallback to null (where is accepted value)
render(){
let name = this.getName(); // this returns `undefined`
return <div>name: {name || null}</div>
}
I have had similar issue.
I was trying to manually update some plugin from node_modules, and when I reverted it back, i got this error.
I solved it by deleting node_modules and running NPM install.
In my case React was not in the scope of the file.
If you import a variable which has jsx from a different file which does not have react imported in it.
import React from "react";
Using following eslint plugin would avoid this: react-in-jsx-scope
Source: https://github.com/yannickcr/eslint-plugin-react/issues/84
In my case, an import was missing. Check your imports!
My solution is just deleting the cached images, files and cookies if you using the Chrome. Settings -> Privacy and security -> Clear browsing data -> Cached image and files / Cookies and other site data