warning : Accessing createClass via the main React package is deprecated - javascript

Reusing code from a library example I got my paypal button working like a charm but now I have this warning comming from that component:
Warning: Accessing createClass via the main React package is deprecated,
and will be removed in React v16.0. Use a plain JavaScript class
instead. If you're not yet ready to migrate, create-react-class v15.*
is available on npm as a temporary, drop-in replacement. For more info
see printWarning #
lowPriorityWarning.js:38 lowPriorityWarning # lowPriorityWarning.js:57
get # React.js:106 register # checkout.lib.js:7165 Component.driver #
checkout.lib.js:5247 ./src/components/presentational/PayPalButton.js #
PayPalButton.js:6
webpack_require
so since the problem is comming from line 6 it might be the way Button is created:
const Button = paypal.Button.driver('react', { React, ReactDOM })
I tried this link provided in the warning but didn't help much and I don't know how to import it or create it differently, this is my complete code:
import React from 'react'
import ReactDOM from 'react-dom'
import paypal from 'paypal-checkout'
import PropTypes from 'prop-types'
const Button = paypal.Button.driver('react', { React, ReactDOM })
export default class PayPalButton extends React.Component {
constructor(props) {
super(props)
this.state = {
env: this.props.env,
client: {
sandbox: this.props.sandboxID,
production: this.props.productionID
},
amount: this.props.amount,
currency: this.props.currency,
commit: this.props.commit
}
}
payment(data, actions) {
return actions.payment.create({
transactions: [
{
amount: { total: this.state.amount, currency: this.state.currency }
}
]
})
}
onAuthorize(data, actions) {
return actions.payment.execute().then((payment_data)=>{
var payment = {}
payment.paid = true
payment.cancelled = false
payment.payerID = data.payerID
payment.paymentID = data.paymentID
payment.paymentToken = data.paymentToken
payment.returnUrl = data.returnUrl
// getting buyer's shipping address and email
payment.address = payment_data.payer.payer_info.shipping_address
payment.email = payment_data.payer.payer_info.email
this.props.paymentDone(payment)
})
.catch(err => {
console.log ('error PayPal'+err)
throw err
})
}
render() {
return (
<Button
commit={ this.state.commit }
env={ this.state.env }
client={ this.state.client }
payment={ (data, actions) => this.payment(data, actions) }
onAuthorize={ (data, actions) => this.onAuthorize(data, actions) }
onCancel={this.props.onCancel}
onError = {this.props.onError}
/>
)
}
}
PayPalButton.propTypes = {
env: PropTypes.string.isRequired,
sandboxID: PropTypes.string,
productionID: PropTypes.string,
amount: PropTypes.number.isRequired,
currency: PropTypes.string.isRequired,
commit: PropTypes.bool.isRequired
}

Related

Access element inside response as object

I have a response from my mongodb database as the following
{_id: '61ca4273e7cc1da1f3dbc9a3', title: 'Hero Syndrome', slug: 'hero-syndrome', category: 'Game', release_date: null, … }
I'm using Redux to fetch the data.
When I do console.log(game) which is the Object I provided, the console return the Object indeed. But when I'm trying to access the children such as title or slug it doesn't work.
I used to have this error Objects are not valid as a React child .. but fixed it somehow randomly in the code.
Any idea how to access title for example ?
What I tried : {title}, title, {game.title} and none of them work
What I did to get data from Redux :
GameComponent.propTypes = {
game: PropTypes.object.isRequired,
};
const mapStateToProps = state => ({
game: state.game,
});
And at the top of the component
function GameComponent({
game: { game, loading, title },
}) { ....
I tried to convert the object to string and to array in order for React to read it but I failed.
Code :
import React, { useState, useEffect } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { getGameByToken } from '../actions/game';
import GameOverview from './GameOverview';
function GameComponent({ game: { game, loading, title }, getGameByToken, auth }) {
useEffect(() => {
getGameByToken(token);
}, [getGameByToken, token]);
return <>
//this doesn't work
Title : {title}
</>;
}
GameComponent.propTypes = {
getGameByToken: PropTypes.func.isRequired,
game: PropTypes.object.isRequired,
auth: PropTypes.object.isRequired,
};
const mapStateToProps = (state) => ({
game: state.game,
auth: state.auth,
});
export default connect(mapStateToProps, { getGameByToken })(GameComponent);
Response from database in redux :
import axios from 'axios';
import { setAlert } from './alert';
import { GET_GAME, GAME_ERROR } from './types';
// GET GAMES BY TOKEN
export const getgameByToken = (token) => async (dispatch) => {
try {
const res = await axios.get('/api/games/' + token);
dispatch({ type: GET_GAME, payload: res.data });
} catch (err) {
dispatch({
type: GAME_ERROR,
payload: {
msg: err.response.msg,
status: err.response.status,
},
});
}
};
From Redux Dev Tools :
EDIT: If I rename game: state.game, to game: state.game.game, I actually got the value ! But when refreshing It goes back saying TypeError: Cannot read properties of null (reading 'title')

How do I validate my api key from stripe?

I have been using stripe checkout in my react application for about a week now. However, I now receive an error that says "Stripe Checkout can't communicate with our payment processor because the API key is invalid. Please contact the website owner or support#stripe.com." I have no idea why this is happening now. I just want to be able to send my total into the stripe modal.
stripe.js
import React, { useState } from "react";
import ReactDOM from "react-dom";
import axios from "axios";
import { connect } from "react-redux";
import { purchase } from "../actions/StoreActions";
import { toast } from "react-toastify";
import StripeCheckout from "react-stripe-checkout";
const mapStateToProps = (state) => {
return {
cart: state.cart,
total: state.total
};
};
const mapDispatchToProps = (dispatch) => {
return {
purchase: (order) => {
dispatch(purchase(order));
}
};
};
function Stripe(props) {
console.log(props);
const [product] = React.useState({
name: `$${props.total}`,
price: props.total
});
async function handleToken(token, address) {
props.startLoading();
const response = await axios.post(
"https://storebe.herokuapp.com/checkout",
{
token,
product
}
);
const { status } = response.data;
if (status === "success") {
props.stopLoading();
console.log(address);
purchaseCartItems(address);
} else {
props.stopLoading();
toast("Failed, please try again", { type: "error" });
}
console.log(response.data);
}
return (
<div className="container">
<StripeCheckout
stripeKey="pk_test_51HF9J6FriexrfnPAT0b3P1wDiKx1YQzONJrB5F4ksTidko10JKZOTgo7zuPjj9NWquykYNnMz1GRyQ5LDI2HvrEF00U49BhKdn"
token={handleToken}
amount={props.total * 100}
billingAddress
shippingAddress
name={product.name}
/>
</div>
);
}
export default connect(mapStateToProps, mapDispatchToProps)(Stripe);
There isn't a way to validate if an API key is actually a valid Stripe API key.
The issue on your end is most likely because the publishable key in your code has a typo in it.
You just have to make sure that the API keys you copy from https://dashboard.stripe.com/test/apikeys are correct and don't have any copy paste errors like extra white space, etc.

I am getting a "no access" error after Oauth facebook login

My buttons pop up and let me login but when it goes to redirect me to the next page, I get an error stating no access from the api and another error saying name isn't defined, I know name is defined because I had this working once before with the same code but then vscode did something stupid and broke it. Here is my code.
import React, {Component} from 'react';
import FacebookLogin from 'react-facebook-login';
import GoogleLogin from 'react-google-login';
import {PostData} from '../../services/PostData';
import {Redirect} from 'react-router-dom';
import './Welcome.css';
class Welcome extends Component {
constructor (props) {
super (props);
this.state = {
loginError: false,
redirect: false,
};
this.signup = this.signup.bind (this);
}
signup (res, type) {
let postData;
if (type === 'facebook' && res.email) {
postData = {
name: res.name,
provider: type,
email: res.email,
provider_id: res.id,
token: res.accessToken,
provider_pic: res.picture.data.url,
};
}
if (type === 'google' && res.w3.U3) {
postData = {
name: res.w3.ig,
provider: type,
email: res.w3.U3,
provider_id: res.El,
token: res.Zi.access_token,
provider_pic: res.w3.Paa,
};
}
if (postData) {
PostData ('signup', postData).then (result => {
let responseJson = result;
sessionStorage.setItem ('userData', JSON.stringify (responseJson));
this.setState ({redirect: true});
});
} else {
}
}
render () {
if (this.state.redirect || sessionStorage.getItem ('userData')) {
return <Redirect to={'/home'} />;
}
const responseFacebook = response => {
console.log ('facebook console');
console.log (response);
this.signup (response, 'facebook');
};
const responseGoogle = response => {
console.log ('google console');
console.log (response);
this.signup (response, 'google');
};
return (
<div>
<FacebookLogin
appId="2580971392000123"
autoLoad={false}
fields="name,email,picture"
callback={responseFacebook}
/>
<br /><br />
<GoogleLogin
clientId="234567891765550-duk7c1do3705dlj8i6dnsr27oe7rlaq3.apps.googleusercontent.com"
buttonText="Login with Google"
onSuccess={responseGoogle}
onFailure={responseGoogle}
/>
</div>
);
}
}
export default Welcome;
So it goes from the welcome component to the Home component, here is the code for Home where the error is.
import React, {Component} from 'react';
import './Home.css';
import {Redirect} from 'react-router-dom';
class Home extends Component {
constructor (props) {
super (props);
this.state = {
name: '',
redirect: false,
products: [],
pid: '',
};
}
componentDidMount () {
let data = JSON.parse (sessionStorage.getItem ('userData'));
console.log (data);
this.setState ({name: data.userData.name});
}
render () {
if (!sessionStorage.getItem ('userData') || this.state.redirect) {
return <Redirect to={'/'} />;
}
if (this.state.pid > 0) {
return <Redirect to={'/checkout'} />;
}
return (
<div>
Welcome {this.state.name}
</div>
);
}
}
export default Home;
Here is the error I am getting:
[HMR] Waiting for update signal from WDS...
react-dom.development.js:20718 Download the React DevTools for a better development experience:
log.js:24 [HMR] Waiting for update signal from WDS...
Home.js:17 {error: {…}}error: {text: "No access"}__proto__: Object
Home.js:19 Uncaught TypeError: Cannot read property 'name' of undefined
at Home.componentDidMount (Home.js:19)
at commitLifeCycles (react-dom.development.js:16855)
at commitAllLifeCycles (react-dom.development.js:18210)
at HTMLUnknownElement.callCallback (react-dom.development.js:149)
at Object.invokeGuardedCallbackDev (react-dom.development.js:199)
at invokeGuardedCallback (react-dom.development.js:256)
at commitRoot (react-dom.development.js:18418)
at completeRoot (react-dom.development.js:19875)
at performWorkOnRoot (react-dom.development.js:19804)
at performWork (react-dom.development.js:19712)
I am new to React and coding in general, so sorry in advance if I sound stupid.
This error means you don't have a valid token/login. Judging by the error Cannot read property 'name' of undefined, I'd say you're trying to get the name property from an object that does not contain it or does not exist (which is more likely). You may have defined name, but that definition is outside the scope of the name call.
The Problem
You are trying to set name in postData to res.name, but res.name is never defined.
The Solution
Find where res is created, and create or add the name property in the constructor.

Error: [vuex] expects string as the type, but found undefined

Studying Vuex. I wrote a simple login page against the example project and the document, but when I tried to use a action function, the developer tool just warned me
Here is my code:
src/views/Login.vue
handleLogin (formName) {
this.$refs[formName].validate(valid => {
if (valid) {
// to do
this.$store.dispatch('user/login', this.loginUser)
} else {
......
})
}
})
src/store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
import user from './modules/User/user'
// import info from './modules/info'
Vue.use(Vuex)
export default new Vuex.Store({
strict: false,
modules: {
user,
// info
}
})
/src/store/modules/User/actions.js
export const userActions = {
login({commit}, loginUser) {
commit(LOGIN)
axios.post(`${ API_BASE_USER }/login`, loginUser)
.then(res => {
console.log(res)
if (res.status == 200) { commit(LOGIN_SUCCESS, res.data) }
else { commit(LOGIN_FAILURE, res.data) }
})
}
}
/src/store/modules/User/user.js
import { userActions } from './actions'
import { userMutations } from './mutations'
export default {
namespaced: true,
state: {
token: ''
},
actions: Object.assign({}, userActions),
mutations: Object.assign({}, userMutations)
}
I got it.
The origin mutations-type.js export const LOGIN = LOGIN
But the correct mutation-type.js should be export const LOGIN = 'LOGIN'
This can also happen when you call $store.commit() without providing it an argument
Had a similar situation, where the Mutation name started with a CAP (), but the actual mutation started with a non cap():
RetrieveContractorSuccess: 'retrieveContractorSuccess'
(before was RetrieveContractorSuccess: 'RetrieveContractorSuccess')

Meteor JS ReactMeteorData - CreateContainer - Super expression must either be null or a function

After upgrading to Meteor 1.5 from 1.4, createContainer function from react-meteor-data gives the following error:
Uncaught TypeError: Super expression must either be null or a function, not undefined
at exports.default (modules.js?hash=fb99b6a…:1144)
at ReactMeteorData.jsx:6
at ReactMeteorData.jsx:6
at createContainer (createContainer.jsx:16)
at AppContainer.jsx (AppContainer.jsx:8)
AppContainer.jsx:
import { Meteor } from 'meteor/meteor';
import { Session } from 'meteor/session';
import { createContainer } from 'meteor/react-meteor-data';
import App from '../layouts/App.jsx';
export default AppContainer = createContainer(props => {
return {
currentUser: Meteor.user(),
};
}, App);
App file below, in constructor i am performing super(props) however error is still thrown
App.jsx:
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
menuOpen: false,
showConnectionIssue: false,
headerTitle: null,
};
this.setHeaderTitle = this.setHeaderTitle.bind(this);
this.logout = this.logout.bind(this);
}
logout() {
Meteor.logout();
this.context.router.replace(`/home`);
}
render() {
... omitted render function
}
}
App.propTypes = {
user: React.PropTypes.object, // current meteor user
connected: React.PropTypes.bool, // server connection status
loading: React.PropTypes.bool, // subscription status
menuOpen: React.PropTypes.bool, // is side menu open?
children: React.PropTypes.element, // matched child route component
location: React.PropTypes.object, // current router location
params: React.PropTypes.object, // parameters of the current route
};
App.contextTypes = {
router: React.PropTypes.object,
};
export default App;
Personnally, for a container data i do like this (from masterchef Base, updated and working as well) :
/* AppContainer.js */
// import react and proptypes ...
import { Meteor } from 'meteor/meteor';
import container from '../../../modules/container';
// Some code for app layout and proptypes...
export default container((props, onData) => {
const user= Meteor.user(); // adapted for your case
onData(null, {
currentUser:user,
// and others data ...
});
}, App);
/* container.js */
import { compose } from 'react-komposer';
import getTrackerLoader from './get-tracker-loader';
export default function container(composer, Component, options = {}) {
return compose(getTrackerLoader(composer), options)(Component);
}
/* get-tracker-loader.js */
import { Tracker } from 'meteor/tracker';
export default function getTrackerLoader(reactiveMapper) {
return (props, onData, env) => {
let trackerCleanup = null;
const handler = Tracker.nonreactive(() => Tracker.autorun(() => {
trackerCleanup = reactiveMapper(props, onData, env);
}));
return () => {
if (typeof trackerCleanup === 'function') trackerCleanup();
return handler.stop();
};
};
}
Hope it ll be useful.
Try following snippet:
export default AppContainer = createContainer((props) => {
// do subscriptions if you have any
return {
currentUser: Meteor.user(),
};
}, App);
You might be missing super() in the App Component.

Categories