How to take values from Formik inside a hook? - javascript

I am using Formik in my app. I need to take values from Formik and use it inside my hook.
Currently I am doing it using useRef hook
Following is my custom hook code which requires Formik values
const { doRequest, errors } = useRequest({
url: "my_url",
method: "post",
body: {
mobileNumber: formikRef.current
? formikRef.current.values.mobileNumber
: "",
password: formikRef.current ? formikRef.current.values.password : "",
},
onSuccess: (response) => {
console.log("Hi" + response.msg);
Router.push("/");
},
onFailure: (response) => {
console.log("Hi2" + response.msg);
},
});
In the body, the mobile number and password is always empty even though I enter values in my textfield. I am calling the doRequest method inside onSubmit of Formik
I am asking the ref using following
<Formik
innerRef={formikRef}..
If I had used useState for all my fields It would have been extremely easy to pass those values to my custom hook but due to large form and validation , I am using Formik

You don't need to use innerRef. You can simply use formik values.
Your custom hook should return doRequest which accepts a param so that it can catch dynamic values.
write the hook in such a way that it caters to both static values and dynamic values. See the closed github issue here
working demo
Code snippet
export default () => {
const { doRequest, errors } = useRequest({
url: "my_url",
method: "post",
body: {
mobileNumber: "0000",
password: "xxxx"
},
onSuccess: response => {
console.log("Hi" + response.msg);
// Router.push("/");
},
onFailure: response => {
console.log("Hi2" + response.msg);
}
});
const handleSubmit = (values, actions) => {
alert(JSON.stringify(values, null, 2));
actions.setSubmitting(false);
doRequest(values);
};
return (
<div className="col-sm-12">
<h1>My Form</h1>
<Formik initialValues={{ mobileNumber: "" }} onSubmit={handleSubmit}>
{({ errors }) => (
<Form>
<Field name="mobileNumber" placeholder="Mobile Number" />
<Field name="password" placeholder="Password" />
<div className="messages-wrapper">
{errors.email && (
<div className="alert alert-danger">
<ErrorMessage name="mobileNumber" />
</div>
)}
{errors.password && (
<div className="alert alert-danger">
<ErrorMessage name="password" />
</div>
)}
</div>
<button className="btn btn-primary" type="submit">
Submit
</button>
</Form>
)}
</Formik>
</div>
);
};

You can get any value from the Formik bag via the useFormikContext() hook. Like so:
const { values } = useFormikContext();
const { mobileNumber } = values;

You could use the predefined useFormikContext() hook provided by Formik or you could set a ref to Formik and use its current value to fetch Formik form values.

Related

Antd with formik setFieldValue

There is a Antd table with data, when i click to button "Change", the entire line with data is passed to the function in the form of an object, now it remains to insert data into the fields, but I can't, what should I do?
How set data to antd input using outside function?
I can do it with .map (), but it seems more appropriate to me to use formik
const BankForm = (props) => {
const [form] = Form.useForm();
//show close form
const columns = [
...MY columns
{
title: "Действие",
key: "action",
fixed: "right",
render: (text, record) => (
<Space size="middle"
I clink to Button and all data of row go to ChangeBank(record)
<a onClick={() => ChangeBank(record)}> Изменить</a>
</Space>
),
},
];
const formik = useFormik({
initialValues: {
name_bank: "",
},
validate,
onSubmit: (values) => {
},
});
//my function to set data to form
let ChangeBank = (record) => {
formik.setFieldValue("name_bank", record.name_bank);
};
return (
<div className={clas.tableBlock_header}>
my form
<Form
form={form}
layout="vertical"
hideRequiredMark
onFinish={formik.handleSubmit}
>
<Form.Item
name="name_bank"
label="Название банка"
rules={[{ required: true, message: "Введите название банка" }]}
>
<Input value={formik.values.name_bank} name="name_bank" />
</Form.Item>
</Form>
);
};
If you want to set values in antd form fields with formik, dont give the name Form.item
AND if you want use antd with formik, and you need validaite your inputs just download Yup. Dont use antd menthods.
Yup with formik
<Form
form={form}
layout="vertical"
hideRequiredMark
onFinish={formik.handleSubmit}
>
<Form.Item
label="Название банка"
rules={[{ required: true, message: "Введите название банка" }]}
>
<Input value={formik.values.name_bank} name="name_bank" />
</Form.Item>
</Form>**strong text**

Yup 'notRequired' method doesn't seem to be working in my form validation

I am using Yup to validate my form fields.
I want the user to paste their instagram URL into the input field. It is not a required field but if they do start to type, the string must match the regex. The regex works, however the 'invalid url' message still displays if the user doesn't type anything, even although the field should not be required. I have tried the following but it still doesn't work. Any suggestions?
const validationSchema = Yup.object().shape({
instagram: Yup.string()
.notRequired()
.matches(
/(?:(?:http|https):\/\/)?(?:www.)?(?:instagram.com|instagr.am)\/([A-Za-z0-9-_]+)/im,
'invalid url'
),
});
In this case you need to use the .nullable() method.
Try this :
const validationSchema = Yup.object().shape({
instagram: Yup.string()
.matches(
/(?:(?:http|https):\/\/)?(?:www.)?(?:instagram.com|instagr.am)\/([A-Za-z0-9-_]+)/im,
'invalid url'
)
.nullable(),
});
Long time no see! I'm not sure if you're using a form state manager or not, but a lot of people seem to use Formik with Yup.
Take a look at this working example using Formik with Yup:
Demo Code:
import * as React from "react";
import { Formik } from "formik";
import * as Yup from "yup";
const validationSchema = Yup.object().shape({
instagram: Yup.string()
.notRequired()
.matches(
/(?:(?:http|https):\/\/)?(?:www.)?(?:instagram.com|instagr.am)\/([A-Za-z0-9-_]+)/im,
"Invalid Instagram URL. Example: http(s)://instagram.com/janedoe"
)
});
const ValidatedInstagramForm = () => {
const handleFormSubmit = (values, { setSubmitting }) => {
alert(
`Validated form was submitted with:\n${JSON.stringify(values, null, 4)}`
);
setSubmitting(false);
};
return (
<Formik
initialValues={{ instagram: "" }}
onSubmit={handleFormSubmit}
validationSchema={validationSchema}
>
{({
errors,
handleBlur,
handleChange,
handleSubmit,
isSubmitting,
values,
touched
}) => (
<form className="form" onSubmit={handleSubmit}>
<div className="input-container">
<label className="label" htmlFor="instagram">
Instagram
</label>
<input
name="instagram"
type="text"
placeholder="Enter your instagram (optional)..."
value={values.instagram}
onChange={handleChange}
onBlur={handleBlur}
className="input"
style={{
background:
errors.instagram && touched.instagram
? "rgba(255, 0, 0, 0.25)"
: "",
borderColor: errors.instagram && touched.instagram ? "red" : ""
}}
/>
{errors.instagram && touched.instagram && (
<div className="error">{errors.instagram}</div>
)}
</div>
<button className="button" type="submit" disabled={isSubmitting}>
Submit
</button>
</form>
)}
</Formik>
);
};
export default ValidatedInstagramForm;
If you're not using a form state manager, then you could always manually validate the input on form submit instead of on input change:
Demo Code:
import * as React from "react";
const ValidatedInstagramForm = () => {
const [value, setValue] = React.useState("");
const [error, setError] = React.useState("");
const handleChange = ({ target: { value } }) => {
setValue(value);
setError("");
};
const isValidInput = (value) => {
if (!value) return "";
return /(?:(?:http|https):\/\/)?(?:www.)?(?:instagram.com|instagr.am)\/([A-Za-z0-9-_]+)/im.test(
value
)
? ""
: "Invalid Instagram URL. Example: http(s)://instagram.com/janedoe";
};
const handleSubmit = (event) => {
event.preventDefault();
const error = isValidInput(value);
if (!error)
alert(
`Validated form was submitted with:\n${JSON.stringify(
{ instagram: value },
null,
4
)}`
);
else setError(error);
};
return (
<form className="form" onSubmit={handleSubmit}>
<div className="input-container">
<label className="label" htmlFor="instagram">
Instagram
</label>
<input
name="instagram"
type="text"
placeholder="Enter your instagram (optional)..."
value={value}
onChange={handleChange}
className="input"
style={{
background: value && error ? "rgba(255, 0, 0, 0.25)" : "",
borderColor: value && error ? "red" : ""
}}
/>
{value && error ? <div className="error">{error}</div> : null}
</div>
<button className="button" type="submit" disabled={error}>
Submit
</button>
</form>
);
};
export default ValidatedInstagramForm;
In fact, there are two definitions of .matches() method :
string.matches(regex: Regex, message?: string | function)
string.matches(regex: Regex, options: { message: string, excludeEmptyString: bool })
Both are matching the Regexp passed in argument, but the second one short circuits the test when the value is an empty string (notice that now the message should be in the options object).
So in your case, you should use the second definition. Here is the correct code (you don't need to include .notRequired method) :
const validationSchema = Yup.object().shape({
instagram: Yup.string()
.matches(
/(?:(?:http|https):\/\/)?(?:www.)?(?:instagram.com|instagr.am)\/([A-Za-z0-9-_]+)/im,
{
message: 'invalid url',
excludeEmptyString: true,
}
),
});
I had several problems in this matter, so this is my take, and solution. e.g. Allowed null, or if they were filled in then they had to have an min length.
taxid: Yup.string()
.nullable()
.notRequired()
.transform(x => x === '' ? undefined : x)
.min(5, 'TaxID must be at least 5 characters'),
corpname: Yup.string()
.nullable()
.notRequired()
.transform(x => x === '' ? undefined : x)
.min(2, 'Company name must be at least 2 characters'),
postno: Yup.string()
.required('Post number is required')
.min(4, 'Post number must be at least 4 characters'),

Identifying what item have been deleted (created and modifed) in a Formik FieldArray

Was wondering if Formik has a native solution for identifying the addition and deletion (and update) of FieldArray in the form ?
I have the code on sandbox here https://codesandbox.io/s/jn7x2m75o9 ( based on the original Formik Array example # https://github.com/jaredpalmer/formik/blob/master/examples/Arrays.js )
but also the relevant part here :
With an Initial state of 3 friend defined, how can I know in my onSubmithandler which one were modified,deleted,updated.
import React from "react";
import { Formik, Field, Form, ErrorMessage, FieldArray } from "formik";
const initialValues = {
friends: [
{
name: "Friend_A",
email: "email_A#somewhere.com"
},
{
name: "Friend_B",
email: "email_B#somewhere.com"
},
{
name: "Friend_C",
email: "email_C#somewhere.com"
}
]
};
const mySubmit = values => console.log();
const SignIn = () => (
<div>
<h1>Invite friends</h1>
<Formik
initialValues={initialValues}
onSubmit={values => {
var itemRemoved = values.GetItemRemoveFromArray; // This is what I'm looking for
console.log(itemRemoved);
// Would print Friend_A
var itemAdded = values.GetItemAddedFromArray; // This is what I'm looking for
console.log(itemAdded);
// Would print New_Friend
var itemUpdated = values.GetItemUpdatedInArray; // This is what I'm looking for
console.log(itemUpdated);
// Would print Friend_C
setTimeout(() => {
alert(JSON.stringify(values, null, 2));
}, 500);
}}
render={({ values }) => (
<Form>
<FieldArray
name="friends"
render={({ insert, remove, push }) => (
<div>
{values.friends.length > 0 &&
values.friends.map((friend, index) => (
<div className="row" key={index}>
<div className="col">
<label htmlFor={`friends.${index}.name`}>Name</label>
<Field
name={`friends.${index}.name`}
placeholder="Jane Doe"
type="text"
/>
<ErrorMessage
name={`friends.${index}.name`}
component="div"
className="field-error"
/>
</div>
<div className="col">
<label htmlFor={`friends.${index}.email`}>Email</label>
<Field
name={`friends.${index}.email`}
placeholder="jane#acme.com"
type="email"
/>
<ErrorMessage
name={`friends.${index}.name`}
component="div"
className="field-error"
/>
</div>
<div className="col">
<button
type="button"
className="secondary"
onClick={() => remove(index)}
>
X
</button>
</div>
</div>
))}
<button
type="button"
className="secondary"
onClick={() => push({ name: "", email: "" })}
>
Add Friend
</button>
</div>
)}
/>
<button type="submit">Invite</button>
</Form>
)}
/>
</div>
);
export default SignIn;
So if with the above a user where to :
Click on the X below Friend_A
Modify Friend_C email to email_C#nothere.com
Click "Add Friend"
Enter value Name: New_Friend_X and email: XX#YY.com
Click "Add Friend"
Enter value Name: New_Friend_Z and email: Friend_Z#coolplace.com
Click "X" button below newly entered "New_Friend_X"
Click "Invite"
in my mySubmit I'm looking for a way to easily get :
Friend_A was Removed
Friend_C was Modified
New_Friend_Z was added (was not in the original initialValues to formik)
(I Don't care about New_Friend_X. No need to know it was added/removed )
Point of this is to minimize rest call to the back end to create/update entity/link and also I really dont want to write my own "secondary state" in the onClick handler of the remove button before calling the remove(index) handler provided by Formik to track what need to be deleted from the DB.
Its not built into Formik, but it is not hard to do in javascript.
First, understand that Formik clones the object you give to initialValues. So in onSubmit, you will compare the final value to your original object.
The incoming data:
const initialFriends = [
{
name: "Friend_A",
email: "email_A#somewhere.com"
},
{
name: "Friend_B",
email: "email_B#somewhere.com"
},
{
name: "Friend_C",
email: "email_C#somewhere.com"
}
];
const initialValues = { friends: initialFriends };
Modified Formik declaration:
<Formik initialValues={initialValues}
...
onSubmit={values => {
const { added, deleted, changed } = addDeleteChange(
initialFriends,
values.friends
);
setTimeout(() => {
alert(
"Added: " + JSON.stringify(Object.fromEntries(added.entries()))
);
alert(
"Deleted: " + JSON.stringify(Object.fromEntries(deleted.entries()))
);
alert(
"Changed:" + JSON.stringify(Object.fromEntries(changed.entries()))
);
alert(JSON.stringify(values, null, 2));
}, 500);
}}
...
Helper functions:
function partition(array, filter) {
let pass = [],
fail = [];
array.forEach(e => (filter(e) ? pass : fail).push(e));
return [pass, fail];
}
const addDeleteChange = (in1, out1) => {
let inMap = new Map(in1.map(f => [f.name, f]));
let outMap = new Map(out1.map(f => [f.name, f]));
let inNames = new Set(inMap.keys());
let outNames = new Set(outMap.keys());
let [kept, added] = partition(out1, f => inNames.has(f.name));
let deleted = in1.filter(f => !outNames.has(f.name));
//alert(JSON.stringify(Object.fromEntries(deleted.entries())));
let changed = kept.filter(f => f.email !== inMap.get(f.name).email);
//alert(JSON.stringify(Object.fromEntries(changed.entries())));
return { added: added, deleted: deleted, changed: changed };
};
Code in codesandbox
NOTE: If you change the name of a friend, that will appear as a delete of original friend and an add of a new friend.
A more robust solution would be to add a (hidden) "id" field to each friend. Then instead of comparing name, would compare id.
That requires generating a new id as add each friend.

How to properly use Formik's setError method? (React library)

I am using React communicating with a backend. Now trying to properly implement Formik (Form library).
Main question:
How do I properly use Formik's setError method?
Client side validation errors show properly, but now I am trying to set/show the backend validation errors, which are returned with a response with status code 400.
Link to the docs on the method I am trying to use
I am using this method in the method named handle400Error in the code below.
My React (and Formik) code:
import React, { Component } from "react";
import axios from "axios";
import { Formik } from "formik";
import * as Yup from "yup";
import styled from "styled-components";
import FormError from "../formError";
const Label = styled.label``;
class LoginForm extends Component {
initialValues = {
password: "",
username: ""
};
getErrorsFromValidationError = validationError => {
const FIRST_ERROR = 0;
return validationError.inner.reduce((errors, error) => {
return {
...errors,
[error.path]: error.errors[FIRST_ERROR]
};
}, {});
};
getValidationSchema = values => {
return Yup.object().shape({
password: Yup.string()
.min(6, "Password must be at least 6 characters long")
.required("Password is required!"),
username: Yup.string()
.min(5, "Username must be at least 5 characters long")
.max(40, "Username can not be longer than 40 characters")
.required("Username is required")
});
};
handleSubmit = async (values, { setErrors }) => {
console.log("handleSubmit");
try {
const response = await axios.post(
"http://127.0.0.1:8000/rest-auth/login/",
values
);
const loginToken = response.data["key"];
this.handleLoginSuccess(loginToken);
} catch (exception) {
// Expected: 400 status code
if (exception.response && exception.response.status === 400) {
// Display server validation errors
this.handle400Error(exception.response.data, setErrors);
}
console.log("exception", exception);
console.log("exception.response", exception.response);
}
};
handle400Error = (backendErrors, setErrors) => {
let errors = {};
for (let key in backendErrors) {
errors[key] = backendErrors[key][0]; // for now only take the first error of the array
}
console.log("errors object", errors);
setErrors({ errors });
};
handleUnexpectedError = () => {};
handleLoginSuccess = loginToken => {
console.log("handleLoginSuccess");
this.props.setGreeneryAppState({
loginToken: loginToken
});
this.props.history.replace(`/${this.props.locale}/`);
};
validate = values => {
const validationSchema = this.getValidationSchema(values);
try {
validationSchema.validateSync(values, { abortEarly: false });
return {};
} catch (error) {
return this.getErrorsFromValidationError(error);
}
};
render() {
return (
<React.Fragment>
<h1>Login</h1>
<Formik
initialValues={this.initialValues}
validate={this.validate}
validationSchema={this.validationSchema}
onSubmit={this.handleSubmit}
render={({
errors,
touched,
values,
handleBlur,
handleChange,
handleSubmit
}) => (
<form onSubmit={handleSubmit}>
{errors.non_field_errors && (
<formError>{errors.non_field_errors}</formError>
)}
<Label>Username</Label>
<input
onChange={handleChange}
onBlur={handleBlur}
value={values.username}
type="text"
name="username"
placeholder="Enter username"
/>
{touched.username &&
errors.username && <FormError>{errors.username}</FormError>}
<Label>Password</Label>
<input
onChange={handleChange}
onBlur={handleBlur}
value={values.password}
type="password"
name="password"
placeholder="Enter password"
/>
{touched.password &&
errors.password && <FormError>{errors.password}</FormError>}
<button type="submit">Log in</button>
</form>
)}
/>
</React.Fragment>
);
}
Formik author here...
setError was deprecated in v0.8.0 and renamed to setStatus. You can use setErrors(errors) or setStatus(whateverYouWant) in your handleSubmit function to get the behavior you want here like so:
handleSubmit = async (values, { setErrors, resetForm }) => {
try {
// attempt API call
} catch(e) {
setErrors(transformMyApiErrors(e))
// or setStatus(transformMyApiErrors(e))
}
}
What's the difference use setStatus vs. setErrors?
If you use setErrors, your errors will be wiped out by Formik's next validate or validationSchema call which can be triggered by the user typing (a change event) or blurring an input (a blur event). Note: this assumed you have not manually set validateOnChange and validateOnBlur props to false (they are true by default).
IMHO setStatus is actually ideal here because it will place the error message(s) on a separate part of Formik state. You can then decide how / when you show this message to the end user like so.
// status can be whatever you want
{!!status && <FormError>{status}</FormError>}
// or mix it up, maybe transform status to mimic errors shape and then ...
{touched.email && (!!errors.email && <FormError>{errors.email}</FormError>) || (!!status && <FormError>{status.email}</FormError>) }
Be aware that the presence or value of status has no impact in preventing the next form submission. Formik only aborts the submission process if validation fails.
const formik = useFormik({
initialValues:{
email:"",password:"",username:""
},
validationSchema:validation_schema,
onSubmit:(values) => {
const {email,password,username} = values
// ......
}
});
formik.setErrors({email:"Is already taken"}) // error message for email field
I just solved my own problem.
I needed to use:
setErrors( errors )
instead of:
setErrors({ errors })
Another way to handle this situation is to assign a specific key to your api errors and use setStatus for status messages.
__handleSubmit = (values, {setStatus, setErrors}) => {
return this.props.onSubmit(values)
.then(() => {
setStatus("User was updated successfully.");
})
.catch((err) => {
setErrors({api: _.get(err, ["message"])});
});
}
Then any validation errors would appear by the fields and any api errors could appear at the bottom:
<Formik
validationSchema={LoginSchema}
initialValues={{login: ""}}
onSubmit={this.__handleSubmit}
>
{({isSubmitting, status, errors, values, setFieldValue}) => (
<Form className={classNames("form")}>
<FormGroup>
<InputGroup>
<InputGroup.Text>
<FontAwesomeIcon icon={faUser} fixedWidth />
</InputGroup.Text>
<Field
name="login"
type={"text"}
placeholder="Login"
className="form-control"
/>
</InputGroup>
<ErrorMessage name="login" />
</FormGroup>
<Button type="submit" variant="primary" disabled={isSubmitting}>
Submit
</Button>
{errors && _.has(errors, ["api"]) && <div className="text-danger">{_.get(errors, ["api"])}</div>}
{status && <div className="text-success">{status}</div>}
</Form>
)}
</Formik>
Don't forget about the schema...
const LoginSchema = Yup.object().shape({
login: Yup.string()
.min(4, 'Too Short!')
.max(70, 'Too Long!')
.required('Login is required'),
});
The api error message will show until the next validation call by Formik (i.e. the user is fixing something). But the status message will stay until you clear it (with a timer or Fade).
This what you're looking
setErrors({ username: 'This is a dummy procedure error' });
<Formik
validationSchema={schema}
initialValues={{ email: '', pswrd: '' }}
onSubmit={(values, actions) => {
// initialise error status <---- 1
actions.setStatus(undefined);
setTimeout(() => {
// setting error status <---- 2
actions.setStatus({
email: 'This is email already exists.',
pswrd: 'This is password is incorrect',
});
}, 500);
}}
// destructuring status <---- 3
render={({ handleSubmit, handleChange, handleBlur, values, errors, status }) => (
<form onSubmit={handleSubmit}>
<input
type="text"
name="email"
value={values['email']}
onChange={handleChange}
onBlur={handleBlur}
/>
<input
type="text"
name="pswrd"
value={values['pswrd']}
onChange={handleChange}
onBlur={handleBlur}
/>
<button type="submit">Submit</button>
// using error status <---- 4
{status && status.email ? (
<div>API Error: {status.email}</div>
) : (
errors.email && <div>Validation Error: {errors.email}</div>
)}
{status && status.pswrd ? (
<div>API Error: {status.pswrd}</div>
) : (
errors.pswrd && <div>Validation Error: {errors.pswrd}</div>
)}
</form>
)}
/>

Warning: Failed prop type: Invalid prop `initialValues` supplied to `Form(AddComment)`

My application has dynamic routes (dynamic route param), in which it contains the redux form.In order to distinguish the form data, I need to post redux form data along with the react route param.
I have passed the react route param as props from the parent component to the child component having the redux form i.e, initial values in props have the param value.I want to initialize the route param to the input field with hidden type.
import React from 'react';
import { Field, reduxForm,propTypes } from 'redux-form';
import submit from '../actions/commentActions'
import connect from 'react-redux';
const validate = values => {
const errors = {}
if (!values.email) {
errors.email = 'Required'
} else if (!/^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(values.email)) {
errors.email = 'Invalid email address'
}
if (!values.message) {
errors.message = 'Required !!'
}else if (values.message.length > 15) {
errors.message = 'Must be 15 characters or less'
}
return errors
}
const renderField = ({
input,
label,
type,
meta: { touched, error, warning }
}) => (
<div>
<div>
<input {...input} placeholder={label} type={type} className="form-control" />
{touched &&
((error && <span className="text-danger">{error}</span>) )}
</div>
</div>
)
const renderTextAreaField = ({
input,
label,
type,
meta: { touched, error, warning }
}) => (
<div>
<div>
<textarea {...input} rows="3" placeholder={label}
className="form-control shareThought mt-1"></textarea>
{touched &&
((error && <span className="text-danger">{error}</span>) )}
</div>
</div>
)
const AddComment = props => {
const { error,handleSubmit, pristine, reset, submitting,initialValues } = props;
// console.log(initialValues); prints route param i.e honda
// console.log(props);
return (
<div className="leaveComment pb-2">
<form onSubmit={handleSubmit(submit)}>
<Field
name="email"
component={renderField}
type="email"
label="Email Id"
placeholder="Enter Email"
/>
<Field name="message"
component={renderTextAreaField}
label="Share Your thought"
type="text"
/>
<Field name="modelname"
type="text"
component="input"
value={initialValues}
hidden
/>
<span className="text-danger">{error && <span>{error}</span>}</span>
<div className="row mx-0" >
<button type="submit" className="btn btn-sm btn-info btn-block mt-2" disabled={pristine || submitting}>Leave a comment</button>
</div>
</form>
</div>
);
};
export default reduxForm({
form: 'addcommentmsg',
validate
})(AddComment);
I solved this issue by passing initialValues with key-value
let initialValues = {
initialValues: {
modelname: this.props.pageId
}
};
Therefore you dont have to define the initialValues either in input field or props.
I also could make it work only this way:
const mapStateToProps = state => {
return {
initialValues: {
status: state.profile.userStatus
}
}
}
And input has such value:
value={props.initialValues}

Categories

Resources