I'm new to react native and i'm trying to send some data to my API,basically a POST request,added a button and trying to call the fetch request using that,but i'm not sure what am i doing wrong in this ??
It says "Please attach method to this component" in the log,let me know if i'm doing anything wrong in this ??
Here's my button
<Button
style={{height: 60,width:150}}
onClick={ () => this.submitNewCustomer()}
title="SUBMIT"
backgroundColor='#C0C0C0'
color="black"
/>
this is my method
submitNewCustomer(){
fetch('http://endpoint.net/api/customerdetail', {
method: 'POST',
headers: new Headers({
'Content-Type': 'application/json', // <-- Specifying the Content-Type
}),
body: JSON.stringify({
CustomerId: '1ef87a90-a941-4ebb-b101-66f74ac07778',
CustomerName: this.state.customername,
UserId:'user2',
VehicleCompanyName:this.state.vehiclecompanyname,
VehicleModelType:this.state.vehiclemodeltype,
VehicleNumber:this.state.vehiclenumber,
CustomerImage:'',
Location:'',
CustomerImageType:'png'
}), // <-- Post parameters
})
.then((response) => response.text())
.then((responseText) => {
alert(responseText);
})
.catch((error) => {
console.error(error);
});
}
Any Inputs would be really helpfull
You need to use onPress instead of `onClick, so your button should be
<Button
style={{height: 60,width:150}}
onPress={ () => this.submitNewCustomer()}
title="SUBMIT"
backgroundColor='#C0C0C0'
color="black"
/>
Related
I am trying to setup a Sendgrid Newletter signup, using the following code, stored in pages/api
import axios from "axios";
export default async function handler(req, res) {
if (req.method === "PUT") {
axios
.put(
"https://api.sendgrid.com/v3/marketing/contacts",
{
contacts: [{ email: `${req.body.mail}` }],
list_ids: [process.env.SENDGRID_MAILING_ID],
},
{
headers: {
"content-type": "application/json",
Authorization: `Bearer ${process.env.SENDGRID_SECRET}`,
},
}
)
.then((result) => {
// return
res.status(200).send({
message:
"Your email has been succesfully added to the mailing list. Welcome 👋",
});
})
.catch((err) => {
// return
res.status(500).send({
message:
"Oups, there was a problem with your subscription, please try again or contact us",
});
});
}
}
The front end component looks similar to
import axios from "axios";
import { toast } from "react-toastify";
import { useState } from "react";
const MailingList = () => {
const [mail, setMail] = useState(null);
const [loading, setLoading] = useState(false);
const subscribe = () => {
setLoading(true);
axios
.put("api/mailingList", {
mail,
})
.then((result) => {
if (result.status === 200) {
toast.success(result.data.message);
setLoading(false);
}
})
.catch((err) => {
console.log(err);
setLoading(false);
});
};
return (
<div className='my-10'>
<hr className='my-5' />
<h2 className='text-3xl md:text-3xl font-semibold font-title'>
Stay Tuned!
</h2>
<label className='label'>
<p className='text-lg max-w-xl text-center m-auto leading-9'>
Want to be the first to know when SupaNexTail launches and get an
exclusive discount? Sign up for the newsletter!
</p>
</label>
<div className='mt-5'>
<input
onChange={(e) => {
setMail(e.target.value);
}}
type='email'
placeholder='Your email'
className='input input-primary input-bordered'></input>
<button
onClick={subscribe}
className={`btn ml-3 ${
loading ? "btn-disabled loading" : "btn-primary"
}`}>
I'm in!
</button>
</div>
<hr className='my-5' />
</div>
);
};
export default MailingList;
The emails are actually being added to the Sendgrid mailing list, but no response error is being displayed, email field is not cleared. And this is displayed in the console:
API resolved without sending a response for /api/MailingList, this may result in stalled requests.
The same console warning is displayed when return res.status(..
Need some advice on how to solve this!
I am trying to make a secure authentication with next.js
I've followed this article because it shows how do to it with api route and proxy server, but I do not understand why he uses this http-proxy module
I did the same thing without it and it seems to work perfectly fine.
Here is my pages/login.js file
import { Button } from '#mui/material'
import { useState } from 'react'
export default function loginPage() {
const [message, setMessage] = useState();
const handleSubmit = async (event) => {
event.preventDefault();
const data = {
username: event.target.username.value,
password: event.target.password.value
};
const response = await fetch('/api/login', {
headers: {
'Content-Type': 'application/json'
},
method: 'POST',
body: JSON.stringify(data),
});
setMessage(response.message);
}
return (
<div className="block">
<form onSubmit={handleSubmit}>
{message ? <p className="message">{message}</p> : ""}
<label htmlFor="first">Username</label>
<input type="text" id="username" name="username" variant="outlined" required />
<label htmlFor="last">Password</label>
<input type="text" id="password" name="password" variant="outlined" required />
<div>
<Button className="btn" type="submit" variant="outlined">Submit</Button>
</div>
</form>
</div>
)
}
Here is my pages/api/[...catchAll].js
import Cookies from "cookies"
export default async function handler(req, res) {
console.log("HERE");
const response = await fetch("http://localhost:7000/register", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(req.body)
}).then((res) => res.json());
const cookies = new Cookies(req, res);
cookies.set("authorization", response.token, {
httpOnly: true,
sameSite: "lax",
maxAge: 100000
});
res.status(200).json(response)
}
My front-end pages/login.js sends a request to pages/api[...catchAll].js and then a request to my back-end is being made. My back-end returns
{
message: "success",
token: crypto.randomBytes(48).toString('hex')
}
and then pages/api/[...catchAll].js sets my cookies. Why in the article the person uses the httpProxy module ? Is it more secure ? Why ?
I've seen this technique in a lot of places because of secure measurements, but I do not understand why they use this proxy server.
Could someone please explain ?
The aim of my application is to take a URL submitted by a user in a form, pull data from it, manipulate that data, and then submit the manipulated data to a Postgres database.
Current Status
So far I have developed a form on the front end of the application (irrelevant validation / styling code has been removed from this excerpt):
const Feeds = ({ visible }) => {
const handleSubmit = async (e) => {
e.preventDefault();
try {
const body = { feedTitle, websiteUrl, currency, feedUrl };
await fetch('/api/form', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body)
});
console.log('body: ', body);
} catch (error) {
console.error(error);
}
};
return (
<Form onSubmit={(e) => handleSubmit(e)} id="myForm" visible={visible}>
<HeaderContainer>
<Header>Add a new feed</Header>
<HeaderDescription>Please complete all of the required fields below and submit to add a new feed.</HeaderDescription>
</HeaderContainer>
<FormContainer>
<InputContainer>
<Label>Feed title</Label>
<Input type="text" placeholder="" value={feedTitle} onChange={(e) => handleChangeFeedTitle(e)} />
</InputContainer>
<InputContainer>
<Label>Website url</Label>
<Input type="text" placeholder="" value={websiteUrl} onChange={(e) => handleChangeWebsiteUrl(e)} />
</InputContainer>
<InputContainer>
<Label>Currency</Label>
<Select onChange={(e) => handleChangeCurrency(e)} name="currency" id="currency-select">
{currencies.map((option, index) => (
<option key={index} value={option.value}>
{option.text}
</option>
))}
</Select>
</InputContainer>
<InputContainer>
<Label>Feed url</Label>
<Input type="text" placeholder="" value={feedUrl} onChange={(e) => handleChangeFeedUrl(e)} />
</InputContainer>
</FormContainer>
{allValid ? <Button type="submit" form="myForm">Save</Button> : <DisabledButton>Save</DisabledButton>}
</Form>
)
};
export default Feeds;
On submission, this POST request hits the /api/form API endpoint:
const handler = async (req, res) => {
const body = req.body;
const response = await fetch(body.feedUrl)
.then(res => res.text())
.then(content => console.log(content))
.catch(err => console.error(err));
console.log('body: ', body);
res.status(200).json({ data: `${body}` })
};
export default handler;
Here I have simply console logged the content coming back from the API. Instead I need to manipulate it using a function and then submit the manipulated data to a database using a separate function.
The Problem
My question is, where should I implement these functions so that they trigger on the server side?
Thanks
I am trying to make stripe payments in my react native app using the stripe.charges.create function and library axios. This currently works fine in test mode, so using the secret and publishable test keys. However, when amending the keys to live as well as changing the source I get the following error: [Error: Request failed with status code 408] .
Looking at the stripe docs https://stripe.com/docs/api/errors it appears that this may be due to a missing parameter, ...'Codes in the 4xx range indicate an error that failed given the information provided (e.g., a required parameter was omitted, a charge failed, etc.).'
Could I be missing the customer id in my stripe.charges.create function shown below? The stripe docs mentions that for card sources the customer id is required, https://stripe.com/docs/api/charges/create . If this is required where do I add this in my code in order to make live payments? API Keys obtained from stripe dashboard.
Testing
index.js file
const stripe = require("stripe")("**SK_TEST**");
exports.payWithStripe = functions.https.onRequest((request, response) => {
stripe.charges
.create({
amount: request.body.amount,
currency: request.body.currency,
source: "tok_mastercard",
})
.then((charge) => {
response.send(charge);
})
.catch((err) => {
console.log(err);
});
});
Production
index.js file
const stripe = require("stripe")("SK_LIVE");
exports.payWithStripe = functions.https.onRequest((request, response) => {
stripe.charges
.create({
amount: request.body.amount,
currency: request.body.currency,
source: "request.body.token",
})
.then((charge) => {
response.send(charge);
})
.catch((err) => {
console.log(err);
});
});
CardScreen.js file
import React, { PureComponent } from "react";
import { View, Text, StyleSheet } from "react-native";
import stripe from "tipsi-stripe";
import Button from "./components/Button";
import { demoCardFormParameters } from "./demodata/demodata";
import axios from "axios";
stripe.setOptions({ publishableKey: "PK_LIVE" });
export default class CardScreen extends PureComponent {
static title = "Card Form";
state = {
loading: false,
paymentMethod: null,
};
handleCardPayPress = async () => {
try {
this.setState({ loading: true, paymentMethod: null });
const paymentMethod = await stripe.paymentRequestWithCardForm({
smsAutofillDisabled: true,
});
this.setState({ loading: false, paymentMethod });
} catch (error) {
this.setState({ loading: false });
}
};
makePayment = async () => {
this.setState({ loading: true });
axios({
method: "POST",
url: "https://us-central1-appname-90059.cloudfunctions.net/payWithStripe",
data: {
amount: 50,
currency: "gbp",
token: this.state.paymentMethod,
},
})
.then((response) => {
console.log(response);
this.setState({ loading: false });
})
.catch((err) => {
console.log(err);
});
};
render() {
const { loading, paymentMethod } = this.state;
return (
<View style={styles.container}>
<Text style={styles.header}>Card Form Example</Text>
<Text style={styles.instruction}>
Click button to show Card Form dialog.
</Text>
<Button
text="Enter your card and pay"
loading={loading}
onPress={this.handleCardPayPress}
/>
<View style={styles.paymentMethod}>
{paymentMethod && (
<>
<Text style={styles.instruction}>
Payment Method: {JSON.stringify(paymentMethod.id)}
</Text>
<Button
text="Make Payment"
loading={loading}
onPress={this.makePayment}
/>
</>
)}
</View>
</View>
);
}
}
Thanks.
I'm loading it like that:
const store = createStore(
AppReducer,
composeEnhancers(applyMiddleware(createDebounce(), thunkMiddleware,
websocketMiddleware)),
);
I've got the following action:
export const toggleCardLayersMenu = (index, value) => ({
type: "CARD:TOGGLE_LAYERS_MENU",
index: index,
value: value,
});
Which I dispatch something to open a menu and something to close it.
Now, the chrome extension display the action with a small delay if the action is used to open the menu, and won't display the action at all if it's used to close the menu.
It occurs only with that specific action. What are the possible causes, and what can be done?
Edit:
This is where I dispatch the action:
...
<IconButton
onClick={ e => dispatches.toggleCardLayersMenu(e.currentTarget) }
><LayersIcon />
</IconButton>
<Menu
anchorEl={ card.menuBtnElem }
open={ card.isMenuOpen }
onRequestClose={ () => dispatches.toggleCardLayersMenu(null) }
style={ styles.menu }
>
...
This is the dispatchToProps():
const mapDispatchToProps = (dispatch, ownProps) => ({ dispatches: {
updateCardLayers(value) {
dispatch(displayActions.updateCardLayers(ownProps.index, value));
},
toggleCardLayersMenu(value) {
dispatch(displayActions.toggleCardLayersMenu(ownProps.index, value));
},
...