Leadspedia Form Submission does not work with onSubmit - reactjs

I have a form in React that I'm trying to submit to Leadspedia, but I'm seeing strange behavior. The instructions from Leadspedia API shows an example of using the method and action options to send the form. I'd like to use the onSubmit event handler to have more control of the form, but for some reason that returns with an error. Using their example submits correctly. Here is my code:
const postData = async (url = '', data = {}) => {
const response = await fetch(url, {
method: 'POST',
body: JSON.stringify(data),
});
return response.json();
}
const handleSubmit = async (e) => {
e.preventDefault();
const url = "*leadspedia end point*";
const data = formValues;
postData(url, data)
.then((data) => {
console.log(data)
})
.catch(error => {
console.log(error)
})
resetForm(
Here is my form:
<form
style={{ width: '100%'}}
onSubmit={handleSubmit}
id="lp_form"
action="*leadspedia endpoint*"
method="post"
>
<div>
{formSections?.[formStep]?.fields?.map((field, index) => (
renderInput(field, index)
))}
{Object.keys(formValues).map((key, index) => (
<input key={index} type="hidden" name={key} value={formValues[key]} />
))}
<input type="hidden" id="lp_offer_id" name="lp_offer_id" value={offerId} />
<input type="hidden" id="lp_campaign_id" name="lp_campaign_id" value={campaignId} />
<input type="hidden" id="lp_campaign_key" name="lp_campaign_key" value={campaignKey} />
</div>
<div>
{formStep === 9 && (
<Button type="submit" variant="primary">
Submit
</Button>
)}
</div>
</form>
Submitting without the handleSubmit function works perfectly fine. However, submitting the form with the handleSubmit function returns a response that says Invalid campaign key or id. I've checked the values multiple times and it's the correct key and id. Am I missing something the handleSubmit function that would cause this error?

Related

Unable to make a PATCH request using radio buttons in ReactJS

I am trying to add in a list of tasks and want to change them to either "Complete" or "Not Complete" using radio buttons and then updating it to send a PATCH request to the data to update. When I press update nothing changes on the data.
This is the code I have for this page:
`
function ProjectDetails() {
const [WaxProcedure, setWaxProcedure] = useState("");
const { id } = useParams();
const {
data: project,
error,
isPending,
} = useFetch(`http://localhost:8000/ProjectsData/${id}`);
const history = useNavigate();
const handleClickDelete = () => {
fetch(`http://localhost:8000/ProjectsData/${id}`, {
method: "DELETE",
}).then(() => {
history("/");
});
};
const handleUpdate = () => {
fetch(`http://localhost:8000/ProjectsData/${id}`, {
method: "PATCH",
headers: {
"Content-type": "application/json",
body: JSON.stringify(project),
},
}).then((response) => {
response.json();
});
};
return (
<div className="project-details">
{isPending && <div>Loading...</div>}
{error && <div>{error}</div>}
{project && (
<article>
<h1>{project.Customer}</h1>
<h2>
{project.Part} {project.Description}
</h2>
<h2>{project.Tool}</h2>
<div>Project Status: {project.Stage}</div>
<p>Lead engineer: {project.Engineer}</p>
<div className="procedure-list">
<form onSubmit={handleUpdate}>
Wax: <p>{WaxProcedure}</p>
<input
type="radio"
name="waxprocedure"
value="Not Complete"
required
onChange={(e) => setWaxProcedure(e.target.value)}
/>
Not Complete
<input
type="radio"
name="waxprocedure"
value="Complete"
required
onChange={(e) => setWaxProcedure(e.target.value)}
/>
Complete
<button type="submit" onClick={handleUpdate}>
Update
</button>
</form>
</div>
<button type="submit" onClick={handleClickDelete}>
Delete
</button>
</article>
)}
</div>
);
}
`
Any ideas why the data won't update? I am new to this and spent a long time trying to find an answer.
I have tried the patch request on Postman and this worked too, so nothing wrong with the request.
remove "onsubmit" from form tag and remove type="submit" from both buttons and pass "project" parameter to handleupdate method

unable to display response from post request in react

i am new to react development.
I am able to get response from post request and print in console but nt sure how to display it on main page.
code from app.js for my ui
render() {
return (
<div className="App">
<h1>Enter Email Address to Verify</h1>
<h1>{this.state.response.body}</h1>
<form onSubmit={this.handleSubmit}>
<p>
<strong>Address:</strong>
</p>
<input
type="text"
value={this.state.post}
onChange={e => this.setState({ post: e.target.value })}
/>
<button type="submit">check</button>
</form>
</div>
);
}
this is the way i get it print on console
console.log(wellFormed, validDomain, validMailbox);
handleSubmit = async e => {
e.preventDefault();
const response = await fetch('/api/v1/verifier', {
method: 'POST',
// body: this.state,
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ post: this.state.post }),
});
const body = await response.text();
this.setState({ responseToPost: body });
};
From verifier method
res.send(
`response received , welllformed = ${wellFormed}, validDomain = ${validDomain}, validMailbox = ${validMailbox}`,
)
Most of the time you will get a JSON response which is nothing but an Array of objects. So you can put that to a state then use higher order function map to render each element to the Dom.
let's assume that your response is like this.
[{"activeCases":"5132472","country":"USA"} ,"activeCases":"455602","country":"India"}]
you can refer each object as course(it can be any name) inside the map method.
{this.state.response.map((course) => (
<div>
<h3>Active cases :{course.activeCases}</h3>
<h5>country :{course.country}</h6>
</div>
))}
This will render each data in your repose to the Dom like thise.
Active cases :5132472
country :USA
Active cases :455602
country :India
render() {
return (
<div className="App">
<h1>Enter Email Address to Verify</h1>
<h2>{this.state.response.body}</h2>
<form onSubmit={this.handleSubmit}>
<p>
<strong>Email Address:</strong>
</p>
<input
type="text"
value={this.state.post}
onChange={e => this.setState({ post: e.target.value })}
/>
<button type="submit">Verify</button>
</form>
<p>{this.state.responseToPost}</p>
</div>
);
}
This worked for me

React-Final-Form how to pass props location.search to function

I've been using React-Final-Form for the last few days but I have a lot of issues.
In my main function, PasswordReset, I need the take the prop 'location.search' and pass it to the custom 'handleSubmitOnClick' in order to handle the outcome on submit.
Here the main function:
const handleSubmitOnClick = ({ // I need the location.search to be passed here as prop
password,
password_confirmation,
}) => {
const url = 'http://localhost:3000/api/v1/users/passwords';
const headers = {
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
}
}
const data = {
"user": {
"reset_password_token": location.search,
"password": password,
"password_confirmation": password_confirmation,
}
}
axios.post(url, data, headers)
.then(response => console.log(response))
.catch(error => console.log('error', error)))
}
const PasswordReset = ({
location //<==== I need to pass this to 'handleSubmitOnClick' function
}) =>
<Fragment>
<h1>Password Reset page</h1>
<Form
onSubmit={handleSubmitOnClick}
decorators={[focusOnError]}
>
{
({
handleSubmit,
values,
submitting,
}) => (
<form onSubmit={handleSubmit}>
<Field
name='password'
placeholder='Password'
validate={required}
>
{({ input, meta, placeholder }) => (
<div className={meta.active ? 'active' : ''}>
<label>{placeholder}</label>
<input {...input}
type='password'
placeholder={placeholder}
className="signup-field-input"
/>
{meta.error && meta.touched && <span className="invalid">{meta.error}</span>}
{meta.valid && meta.dirty && <span className="valid">Great!</span>}
</div>
)}
</Field>
<Field
name='password_confirmation'
placeholder='Confirm password'
validate={required}
>
{({ input, meta, placeholder }) => (
<div className={meta.active ? 'active' : ''}>
<label>{placeholder}</label>
<input {...input}
type='password'
placeholder={placeholder}
className="signup-field-input"
/>
{meta.error && meta.touched && <span className="invalid">{meta.error}</span>}
{meta.valid && meta.dirty && <span className="valid">Great!</span>}
</div>
)}
</Field>
<button
type="submit"
className="signup-button"
disabled={submitting}
>
Submit
</button>
</form>
)}
</Form>
</Fragment>
export default PasswordReset;
Any help is REALLY appreciated. A bad answer is better than no answers. Thanks in advance.
You can curry your function to have location updated everytime.
Currying method: (preferred by linters)
const handleSubmitOnClick = (location) => ({ //location would come from PasswordReset every time there's a re-render
^^^^^^^^
password,
password_confirmation,
}) => {
...
}
const PasswordReset = ({
location //<==== I need to pass this to 'handleSubmitOnClick' function
}) =>
<Fragment>
<h1>Password Reset page</h1>
<Form
onSubmit={handleSubmitOnClick(location)} // <--- This will update location on every re-render
decorators={[focusOnError]}
>
{ ... }
</Form>
</Fragment>
export default PasswordReset;
Inline function method:
Alternatively you can use what other answer provided but you still need to update your handleSubmitOnClick function to accept your location prop. It will create new function on every re-render, but because inline functions are bad practice deemed by linters I prefer currying method.
<Form
onSubmit={() => handleSubmitOnClick(location)} // <--- This will create new function on every re-render
decorators={[focusOnError]}
>
<Form
onSubmit={() => handleSubmitOnClick(location)}
decorators={[focusOnError]}
>
Wrap it in an anonymous function that once called, calls your function with the required param, which would be location in this case.
After that the function would have an extra argument:
handleSubmitOnClick = location => ({..props})

Pass input values with React-Final-Form to Axios POST

I have a login page.
Fields: username and password.
On form submit I want to pass the 2 input values to a function which will handle a POST call via Axios API.
Because I am using React-Final-Form, I don't see anyone using refs for the inputs in order to collect the data.
Final-Form provides values as props, but I can't pass them to my external handleClickSignIn function.
const handleClickSignIn = () => {
axios.post(url, data, {
headers: headers
})
.then(response => console.log(response))
.catch(err => console.log(err))
}
const focusOnError = createDecorators();
const SignIn = () =>
<Fragment>
<h1>Sign In page</h1>
<Form
onSubmit={handleClickSignIn}
decorators={[focusOnError]}
>
{
({
handleSubmit,
values,
submitting
}) => (
<form onSubmit={handleSubmit}>
<Field
name='email'
placeholder='Email'
validate={required}
>
{({ input, meta, placeholder }) => (
<div className={meta.active ? 'active' : ''}>
<label>{placeholder}</label>
<input {...input}
type='email'
placeholder={placeholder}
className="signin-field-input"
/>
etc...
you should look at the documentation
onSubmit is a function that will be called with the values of your form
So handleClickSignIn will retrieve the form values in its first argument
const handleClickSignIn = (values) => {
// do what you want with the form values
axios.post(url, values, {headers: headers})
.then(response => console.log(response))
.catch(err => console.log(err))
}

Event code is not executed after default page reload

On onSubmit form event I'd like to send some data to the server with PUT or POST method and then refresh the page, but page reloads without executing the rest of the event code. Adding line event.preventDefault() fixes the issue but blocks reloading. What am I missing?
Event code:
handleFormSubmit = (event, requestType, articleID) => {
const title = event.target.elements.title.value;
const content = event.target.elements.content.value;
switch ( requestType ) {
case 'post':
return axios.post('http://127.0.0.1:8000/api/', {
title: title,
content: content
})
.then(res => console.log(res))
.catch(error => console.err(error));
case 'put':
return axios.put(`http://127.0.0.1:8000 /api/${articleID}/`, {
title: title,
content: content
})
.then(res => console.log(res))
.catch(error => console.err(error));
}
}
Form code:
<Form onSubmit={(event) => this.handleFormSubmit(
event,
this.props.requestType,
this.props.articleID )}>
<FormItem label="Title" >
<Input name="title" placeholder="Put a title here" />
</FormItem>
<FormItem label="Content" >
<Input name="content" placeholder="Enter some content ..." />
</FormItem>
<FormItem>
<Button type="primary" htmlType="submit">{this.props.btnText}</Button>
</FormItem>
</Form>
You need to programmatically reload your page after the form has been submitted successfully, or show an error message when there is no response or any server error:
class App extends React.Component {
handleSubmit = e => {
e.preventDefault();
return axios
.post("https://reqres.in/api/login", {
email: "title",
password: "content"
})
.then(res => {
alert(res.data.token);
location.reload();
})
.catch(error => console.log(error));
};
render() {
return (
<div className="App">
<form onSubmit={this.handleSubmit}>
<input type="text" placeholder="Email" />
<input type="password" placeholder="Password" />
<button type="submit">Submit</button>
</form>
</div>
);
}
}
Here is a demo :https://codesandbox.io/s/j7j00nq705
You can use event.preventDefault(). But you should use react-router library history.push() to manually load another component after your request completes.
case 'post':
return axios.post('http://127.0.0.1:8000/api/', {
title: title,
content: content
})
.then(res => {
console.log(res);
// using "history.push()" to load another component
this.props.history.push('/somePage')
})
.catch(error => console.err(error));
Your above Form component must be routed using react-router or Form component must be in a Component routed using react-router.

Resources