My back-end server is up and running. No problems on that side.
But on my front-end, when I load into the page containing the stripe checkout button, I get the error. And when I click on the button I get a bunch of "failed to load resource" errors. I'm not sure how to expand on this error, the error is accompanied with a long url which I'll append at the bottom. I have gone through the internet and was not able to find a similar issue with a solution.
my component below:
import React from 'react';
import StripeCheckout from 'react-stripe-checkout';
import axios from 'axios';
const StripeCheckoutButton = ({ price }) => {
const priceForStripe = price * 100;
const publishableKey = 'pk_test_6y*************';
const onToken = token => {
axios({
url: 'payment',
method: 'post',
data: {
amount: priceForStripe,
token: token
}
})
.then(response => {
alert('Payment Successfull!');
})
.catch(error => {
console.log('Payment Error: ', console.log(error.message));
alert('There was an issue with your Payment! Please use the provided credit card info.');
});
}
return (
<StripeCheckout
label='Pay Now'
name='Crown Clothing Ltd.'
billingAddress
shippingAddress
image='https://sendeyo.com/up/d/f3eb2117da'
description={`Your total is $${price}`}
amount={priceForStripe}
panelLabel='Pay Now'
token={onToken}
stripeKey={publishableKey}
/>
);
}
export default StripeCheckoutButton;
the urls in the error:
https://q.stripe.com/?event=checkout.config.summary&rf=http%3A%2F%2Flocalhost%3A3000%2Fcheckout&sc=&optchecker-origin=configure&optchecker-numErrors=0&optchecker-numWarnings=0&distinct_id=5bc50a5a-d3bc-56aa-9c8c-1e091f6a7712&eventId=f70f82d3-6f6d-21f9-cb99-9cc0594e70e5&option-key=pk_test_6yhlzR96RC4tBigWRKiPtlIV00iuUf9b6m&h=768&w=1366&lsid=53b5a4be-b37f-4749-9ed6-f33ce3db38e2&cid=de787f0d-a3c9-46d3-95a7-efb4b79d7894&i=1580345068891
https://q.stripe.com/?event=checkout.config.summary&rf=http%3A%2F%2Flocalhost%3A3000%2Fcheckout&sc=&optchecker-origin=configure&optchecker-numErrors=0&optchecker-numWarnings=0&distinct_id=5bc50a5a-d3bc-56aa-9c8c-1e091f6a7712&eventId=f70f82d3-6f6d-21f9-cb99-9cc0594e70e5&option-key=pk_test_6yhlzR96RC4tBigWRKiPtlIV00iuUf9b6m&h=768&w=1366&lsid=53b5a4be-b37f-4749-9ed6-f33ce3db38e2&cid=de787f0d-a3c9-46d3-95a7-efb4b79d7894&i=1580345068891
edit: since i've posted the question, i have tried to run my project from two other PCs and it works alright there. seems to be an issue with my own laptop. i believe it might have to do with an adblock of some kind. i have always had problem with loading ads for some reason, even though i don't have any adblock installed
Related
I'm new in ReactJS. Now trying to make the GET request from an API using axios with the following code. But page loads earlier than the request so my state gives an empty array. I tried to solve it by using async and await but I couldn't succeed it since I don't know the React well, I guess. Please help, thank you a lot.
import {useEffect, useState} from 'react';
import axios from 'axios';
function NewsPage(){
const [news, setNews] = useState([]);
useEffect(() => {
var axios = require("axios").default;
var options = {
method: 'GET',
url: 'https://api.newscatcherapi.com/v2/search',
params: {q: 'obama', lang: 'en', sort_by: 'relevancy', page: '1'},
headers: {
'x-api-key': '**************'
}
};
axios.request(options)
.then(function (response) {console.log(response.data.articles)})
.then(response => setNews(response.data.articles))
.catch(function (error) {console.error(error)})
},[]);
return (
<div>
Hello
{news.map((eachnews) => {
return <div key={eachnews.title}>
<h2>{eachnews.author}</h2>
</div>
})}
</div>
)
}
export default NewsPage
This is normal behavior of React. Older frameworks block the whole page while loading, but React renders the page already while loading.
It is a design decision that makes perfectly sense. You can add a loading animation or a skeleton during loading. This is considered better practice instead of leaving the whole page white. Especially because you can then do good error handling that doesn't interrupt the UI.
I want to integrate React with Django REST API for my ecom website but for some reason that does not work. I really do not know what I missed. Any input is welcomed.
Please see the code below.
REACT
Home.js (this is the code for products)
const loadAllProducts = () => {
getProducts()
.then((data) => {
if(data.error) {
setError(data.error); //box filled with data error
console.log(error); // message "error"
} else {
setProducts(data); // box filled with data product
}
});
loadAllProducts();
};
coreapicalls.js (here I want to fetch the data)
import { API } from "../../backend.js";
export const getProducts = () => {
return fetch(`${API}product`, { method: "GET" })
.then(response => response.json())
.catch((err) => console.log(err));
};
.env (I have both of my servers running, the url and symbol "/" are correct.)
REACT_APP_BACKEND = http://localhost:8000/api/
My compiler returns no specific error.
./src/core/Home.js
Line 16:11: 'loadAllProducts' is assigned a value but never used no-unused-vars
./src/core/Card.js
Line 26:11: 'getAredirect' is assigned a value but never used no-unused-vars
DJANGO (settings.py, Django does give me JSON data on the localhost:8000/api/product/)
'api',
'api.category',
'api.product',
Best,
Rok.
I went into chrome devtools and saw a "cors error" under network. I forgot to run "pip install django-cors-headers" . The configuration on the DJANGO REST API for corsheaders was correct.
I had previously posted this problem under the error message of “Cannot read property 'data' of undefined”. But in the process of digging into it for several hours, I’ve discovered that my problem really boils down to the fact that my “async / await” doesn’t seem to be . . . . awaiting! And yes, I did check the several other versions of this question that have already been asked here. :)
I’m building a React form that will have several drop-down boxes populated with data from MongoDB. I’m relatively new to React and a beginner with MongoDB.
I’ve been able to successfully get the data into the drop-down by just cramming all of the code into one file. Now, I’m trying to start refactoring the code by properly splitting pieces into separate files. And that’s where I’ve run into this “data delay” issue.
When “componentDidMount” calls the “fetchProjects” function, that function goes and grabs a list of projects from MongoDB using the “getProjects” function in a “projects service” file. When the console.log within “fetchProjects” runs, it’s coming back as undefined. But then after the data set comes back as undefined (and errors out the process), I do get a console log of the projects object array from the “getProjects” function.
I’ve been able to make this process work with hard-coded object array data in the “getProjects” function, so that tells me that the problem lies in the amount of time required to actually get the data back from MongoDB.
Please tell me there’s a way to solve this without using Redux! :D
Here’s my App.js file –
import React, { Component } from "react";
import "./App.css";
import { getProjects } from "./services/svcProjects";
class App extends Component {
state = {
data: {
selProject: ""
},
projects: []
};
async componentDidMount() {
await this.fetchProjects();
}
async fetchProjects() {
const { data: projects } = await getProjects();
console.log(projects);
this.setState({ projects });
}
render() {
return (
<div className="App">
<h1>Project Log</h1>
<label htmlFor={"selProject"}>{"Project"}</label>
<select name={"selProject"} id={"selProject"} className="form-control">
<option value="" />
{this.state.projects.map(a => (
<option key={a._id} value={a.project}>
{a.project}
</option>
))}
</select>
</div>
);
}
}
export default App;
And here’s the “projects service” file. Again, please note that the console.log statements here show that I’m still getting data back from MongoDB. That data is just taking too long to arrive back in the App.js file.
Also, by the way, I realize that having my Mongo connection info in this file is a huge security hole. I’ll be fixing that later.
import {
Stitch,
RemoteMongoClient,
AnonymousCredential
} from "mongodb-stitch-browser-sdk";
export function getProjects() {
const client = Stitch.initializeDefaultAppClient("------");
const db = client
.getServiceClient(RemoteMongoClient.factory, "-----")
.db("----------");
client.auth
.loginWithCredential(new AnonymousCredential())
.then(() =>
db
.collection("--------")
.find({}, { sort: { Project: 1 } })
.asArray()
)
.then(res => {
console.log("Found docs", res);
console.log("[MongoDB Stitch] Connected to Stitch");
return res;
})
.catch(err => {
console.error(err);
});
}
I think adding a return into your getProjects() service will solve your issue.
import {
Stitch,
RemoteMongoClient,
AnonymousCredential
} from "mongodb-stitch-browser-sdk";
export function getProjects() { //add async if you need to await in func body
const client = Stitch.initializeDefaultAppClient("------");
const db = client
.getServiceClient(RemoteMongoClient.factory, "-----")
.db("----------"); // if these above are async, then await them as well.
// added return keyword here
return client.auth // should return Promise to await in your component
.loginWithCredential(new AnonymousCredential())
.then(() =>
db
.collection("--------")
.find({}, { sort: { Project: 1 } })
.asArray()
)
.then(res => {
console.log("Found docs", res);
console.log("[MongoDB Stitch] Connected to Stitch");
return res;
})
.catch(err => {
console.error(err);
});
}
Edit 1:
For refactoring, I think pairing redux and redux-saga will give you very good separation of concern and a way to easily write test if you plan to do so.
But overall, I think this tweak above can at least solve your issue.
So I am trying to develop a search bar component in a React application where you can type in a users last name and that request will go to the Behance API and pull up that users data.
I am stuck on this:
axios
.get(API_URL + 'users?q=' + 'matias' + '&client_id=' + API_KEY + '&callback=')
.then(response => {
console.log(response);
})
.catch(error => {
console.log(error);
alert(error.message);
});
I have tried wrapping the above in a const userSearch = () => {}, but that takes me a step farther from my goal. With the above I actually do get 200 statuses, but there is the CORS issue. I just can't seem to put together a callback that is not undefined in there, nevermind that this is a search bar implementation so I am going to have to refactor the above. I was just wanting to see some data returned.
One of the nicest things in Axios, is the seperation between request argument.
For example, the url should be only URL: API_URL + '/users'.
The parameters you want to pass, should be sent as an object.
The promise of the axios get, is the callback you are looking for.
Therefore, your request should look like this:
axios.get(API_URL + 'users', {
params: {
q: 'matias',
client_id: API_KEY,
}
})
.then(response => {
- success callback actions -
})
.catch(error => {
- error callback actions -
});
So I had refactored my axios code and I was still getting CORS errors, but after reading a couple of blogs online saying that with fetch() and jQuery you could get around that, in particular this SO article: Loading Data from Behance API in React Component
I actually duplicated Yasir's implementation like so:
import $ from 'jquery';
window.$ = $;
const API_KEY = '<api-key>';
const ROOT_URL = `https://api.behance.net/v2/users?client_id=${API_KEY}`;
export const FETCH_USER = 'FETCH_USER';
export function fetchUser(users) {
$.ajax({
url: `${ROOT_URL}&q=${users}`,
type: 'get',
data: { users: {} },
dataType: 'jsonp'
})
.done(response => {})
.fail(error => {
console.log('Ajax request fails');
console.log(error);
});
return {
type: FETCH_USER
};
}
And sure enough, no more CORS error and I get back the users data in my Network > Preview tabs. Not very elegant, but sometimes you are just trying to solve a problem and at wits end.
I am new to rxjs Observables. I am trying simple login page application. When I am sending correct credentials, code is working fine and loading spinner also stops rendering. When credentials are invalid then code stops working and spinner also stays on the page. I have to reload the page to make it work again.
Here's the code :
import constants from "../constants";
import "rxjs";
import { ajax } from "rxjs/observable/dom/ajax";
import { loginBody } from "../utils/bodyCreator";
import {
showLoadingSpinner,
hideLoadingSpinner
} from "../actions/LoadingOverlayActions";
const sessionCreated = payload => ({
type: constants.sessionCreated,
response: payload
});
export const tryLoginEpic = (action$, store) =>
action$
.ofType(constants.tryLogin)
.map(() => store.dispatch(showLoadingSpinner()))
.mergeMap(action =>
ajax
.post(constants.loginEndPoint, loginBody(store.getState()), {
"Content-Type": "application/json"
})
.map(data => store.dispatch(sessionCreated(data.response)))
.map(() => store.dispatch(hideLoadingSpinner()))
.catch(err => store.dispatch(hideLoadingSpinner()))
);
Please help me how to do this and what is wrong in this code?
Thanks
You need to use .catch operator in a different way. For example, return empty Observable (or other action), something like:
.catch(error => {
store.dispatch(hideLoadingSpinner());
return Observable.empty();
})
see official documentation on catchError operator