Lose state in React Js - reactjs

I have an application with 2 inputs; name and password. Also, I have a save button that should change the state, using the values from the inputs, in the parent component.
But now, if I insert just one value in one input, I lose the state in the parent component. For example, if I type just name, and click save button, in the parent component I lose the password value, but I don't know why.
How to avoid this using my code?
import React, { useEffect } from "react";
import "./styles.css";
const Test = ({ user, setUser }) => {
const [u, setU] = React.useState("");
const [p, setP] = React.useState("");
function name(e) {
const a = e.target.value;
setU(a);
}
function password(e) {
const a = e.target.value;
setP(a);
}
function save() {
console.log(u);
setUser({ ...user, name: u, password: p });
}
return (
<div>
<input onChange={name} />
<input onChange={password} />
<button onClick={save}>save</button>
</div>
);
};
export default function App() {
const [user, setUser] = React.useState({
name: "",
password: ""
});
useEffect(() => {
setUser({ name: "john", password: "Doe" });
}, []);
return (
<div className="App">
<p>{user.name}</p>
<p>{user.password}</p>
<Test user={user} setUser={setUser} />
</div>
);
}
code link: https://stackblitz.com/edit/react-ytowzg

This should fix your issue:
function save() {
console.log(u);
if(u === '') {
setUser({ ...user, password: p });
} else if (p === '') {
setUser({ ...user, name: u });
} else {
setUser({ ...user, name: u, password: p });
}
}
So, now the state is conditionally updated based on the values of the input fields. The issue with your code is that you're always overwriting the state regardless of the input values.

i have a better proposition,instead of using a separate state variable for name ,password and percentage use a single state variable object
Test.js
import React, { useState } from "react";
import { InputNumber } from "antd";
import "antd/dist/antd.css";
const Test = ({ user, setUser }) => {
const [state, setState] = useState({
name: "",
password: "",
percentage: ""
});
function onChange(e, name) {
setState({
...state,
...(name === undefined
? { [e.target.name]: e.target.value }
: { [name]: e })
});
console.log(state);
}
function save() {
setUser({
...user,
...(state.name !== "" && { name: state.name }),
...(state.password !== "" && { password: state.password }),
...(state.percentage !== "" && { percentage: state.percentage })
});
}
return (
<div>
<input name='name' onChange={onChange} />
<input name='password' onChange={onChange} />
<InputNumber
defaultValue={100}
min={0}
max={100}
formatter={value => `${value}%`}
parser={value => value.replace("%", "")}
onChange={e => onChange(e, "percentage")}
/>
<button onClick={save}>save</button>
</div>
);
};
export default Test;
Updated CodeSandbox here

Related

React-redux useSelector state not working in onSubmit function but working in other functions

Please can someone explain to me why the second implementation of my code is reading the status_code of the msg and my first implementation can't read the status_code of the msg?
First implementation
import { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import PropTypes from 'prop-types';
import { useDispatch, useSelector } from 'react-redux';
import InputField from '../components/layout/InputField';
import { faShop, faGlobe, faHouse, faSign, faMapLocationDot, faCity, faEarthEurope, faUpload } from '#fortawesome/free-solid-svg-icons';
import Button from '../components/layout/Button';
import FormAlert from '../components/layout/FormAlert';
import { createOrUpdateStore, clearMessages } from '../reducers/storeSlice';
const CreateStore = () => {
const [formData, setFormData ] = useState({
name: '',
shop_url: '',
house: '',
street: '',
postalcode: '',
city: '',
country: ''
});
const dispatch = useDispatch();
const { loading, store, msg, errors } = useSelector((state) => state.store);
const navigate = useNavigate();
const {
name,
shop_url,
house,
street,
postalcode,
city,
country,
} = formData;
useEffect(() => {
if (msg) {
dispatch(clearMessages());
}
}, []);
const onChange = (e) => {
setFormData({ ...formData, [e.target.name]: e.target.value });
};
const getError = (name) => {
const findError = errors.filter(error => error.param === name);
if (findErfind errorh > 0) {
const error = errors.find(error => error.param === name);
return error;
}
}
const onSubmit = (e) => {
e.preventDefault();
const result = dispatch(createOrUpdateStore(formData));
if (result) {
if (msg.status_code === '201') {
navigate('/login');
}
}
}
return (
<form onSubmit={(e) => onSubmit(e)} className='dashboard-form'>
<span className='header-text'>Create your store</span>
{JSON.stringify(msg) !== '{}' ? (<FormAlert alert={msg} />) : ''}
<InputField type='text' label='Store name' name='name' value={name} changeHandler={onChange} error={getError('name')} icon={faShop} />
<InputField type='text' label='Website address' name='shop_url' value={shop_url} changeHandler={onChange} error={getError('shop_url')} icon={faGlobe} />
<InputField type='text' label='House' name='house' value={house} changeHandler={onChange} error={getError('house')} icon={faHouse} />
<InputField type='text' label='Street' name='street' value={street} changeHandler={onChange} error={getError('street')} icon={faSign} />
<InputField type='text' label='Postalcode' name='postalcode' value={postalcode} changeHandler={onChange} error={getError('postalcode')} icon={faMapLocationDot} />
<InputField type='text' label='City' name='city' value={city} changeHandler={onChange} error={getError('city')} icon={faCity} />
<InputField type='text' label='Country' name='country' value={country} changeHandler={onChange} error={getError('country')} icon={faEarthEurope} />
<Button text='CREATE' loading={loading} icon={faUpload} />
</form>
)
}
export default CreateStore;
Second implementation
import { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import PropTypes from 'prop-types';
import { useDispatch, useSelector } from 'react-redux';
import InputField from '../components/layout/InputField';
import { faShop, faGlobe, faHouse, faSign, faMapLocationDot, faCity, faEarthEurope, faUpload } from '#fortawesome/free-solid-svg-icons';
import Button from '../components/layout/Button';
import FormAlert from '../components/layout/FormAlert';
import { createOrUpdateStore, clearMessages } from '../reducers/storeSlice';
const CreateStore = () => {
const [formData, setFormData ] = useState({
name: '',
shop_url: '',
house: '',
street: '',
postalcode: '',
city: '',
country: ''
});
const dispatch = useDispatch();
const { loading, store, msg, errors } = useSelector((state) => state.store);
const navigate = useNavigate();
const {
name,
shop_url,
house,
street,
postalcode,
city,
country,
} = formData;
useEffect(() => {
if (msg) {
dispatch(clearMessages());
}
}, []);
const onChange = (e) => {
setFormData({ ...formData, [e.target.name]: e.target.value });
};
const getError = (name) => {
const findError = errors.filter(error => error.param === name);
if (findError.length > 0) {
const error = errors.find(error => error.param === name);
return error;
}
}
const onSubmit = (e) => {
e.preventDefault();
dispatch(createOrUpdateStore(formData));
}
const redirectOnSuccess = (msg) => {
if (msg.status_code === '201') {
setTimeout(() => {
dispatch(clearMessages());
}, 2000);
setTimeout(() => {
dispatch(clearMessages());
navigate('/store');
}, 3000);
}
}
redirectOnSuccess(msg);
return (
<form onSubmit={(e) => onSubmit(e)} className='dashboard-form'>
<span className='header-text'>Create your store</span>
{JSON.stringify(msg) !== '{}' ? (<FormAlert alert={msg} />) : ''}
<InputField type='text' label='Store name' name='name' value={name} changeHandler={onChange} error={getError('name')} icon={faShop} />
<InputField type='text' label='Website address' name='shop_url' value={shop_url} changeHandler={onChange} error={getError('shop_url')} icon={faGlobe} />
<InputField type='text' label='House' name='house' value={house} changeHandler={onChange} error={getError('house')} icon={faHouse} />
<InputField type='text' label='Street' name='street' value={street} changeHandler={onChange} error={getError('street')} icon={faSign} />
<InputField type='text' label='Postalcode' name='postalcode' value={postalcode} changeHandler={onChange} error={getError('postalcode')} icon={faMapLocationDot} />
<InputField type='text' label='City' name='city' value={city} changeHandler={onChange} error={getError('city')} icon={faCity} />
<InputField type='text' label='Country' name='country' value={country} changeHandler={onChange} error={getError('country')} icon={faEarthEurope} />
<Button text='CREATE' loading={loading} icon={faUpload} />
</form>
)
}
export default CreateStore;
I tried several methods for getting the msg in the onSubmit function but they didn't work. So I read the documentation of the react-redux toolkit and found out that you can use data gotten from the state with useSelector, and that you can use this data in any function but it still refused to work in the onSubmit() function. And this explains why the errors array was retrieved in the getError() function.
Issues
If I had to hazard a guess it is that the createOrUpdateStore is an asynchronous action that should be awaited, and there's a stale closure over the selected msg state in the onSubmit callback. The second implementation skips both these issues by not waiting for any returned Promises from createOrUpdateStore to resolve and relying on the CreateStore component to rerender when the redux state updates.
Solution to fix implementation 1
Assuming this asynchronous createOrUpdateStore action returns a Promise it can be awaited. To overcome the stale msg closure the submit handler will need to manually access the store to get the current state.
// declare submit handler async
const onSubmit = async (e) => {
e.preventDefault();
// await asynchronous action to resolve with result
const result = await dispatch(createOrUpdateStore(formData));
if (result) {
// have result, get msg from current state
const state = store.getState();
const { msg } = state.store;
if (msg.status_code === '201') {
navigate('/login');
}
}
}
Solution to fix implementation 2
The redirectOnSuccess function is called unconditionally as an unintentional side-effect and issues other unintentional side-effect. To make these intentional side-effects the logic should be moved into a useEffect hook with appropriate dependency.
const {
loading,
store,
msg,
errors
} = useSelector((state) => state.store);
const navigate = useNavigate();
...
useEffect(() => {
if (msg.status_code === '201') {
dispatch(clearMessages());
navigate('/store');
}
}, [msg, navigate]);
You have to use a preventDefault to prevent the default submit action and it’s done by the code below:
Const onClick=(event)=>{
event.preventDefault()
// then you can have your redux function calls
}

React and useReducer unable to access the state value

relatively new to React so please excuse me for this question.
Below is a VERY basic form with a submission button and ability to listen for value changes on a users username and password.
The problem that I am facing is that as soon as I type anything into the form, it throws this error:
[![enter image description here][1]][1]
(image isn't uploading: TypeError: Cannot read property "requestInFlight" of undefined)
Apparently state is nowhere to be found. I feel that I have done this verbatim from tutorials and the [documentations][2] so not sure what is throwing me off here.
import React, { useContext, useEffect, useReducer } from "react";
import DispatchContext from "../DispatchContext";
// Boostrap Components
import Form from "react-bootstrap/Form";
import Button from "react-bootstrap/Button";
// Third party Components
import Axios from "axios";
const ACTIONS = {
UPDATE_USERNAME: "update-username",
UPDATE_PASSWORD: "update-password",
REQUEST: "request",
};
const initialState = {
username: "",
password: "",
requestInFlight: false,
};
function reducer(draft, { type, value }) {
switch (type) {
case ACTIONS.UPDATE_USERNAME:
draft.username = value;
return;
case ACTIONS.UPDATE_PASSWORD:
draft.password = value;
return;
case ACTIONS.REQUEST:
draft.requestInFlight = value;
return;
default:
return;
}
}
function FormComponent({ type }) {
const appDispatch = useContext(DispatchContext);
const [state, dispatch] = useReducer(reducer, initialState);
useEffect(() => {
if (!state.requestInFlight) return;
dispatch({ type: ACTIONS.REQUEST, value: true });
const ourRequest = Axios.CancelToken.source();
async function sendRequest() {
try {
const response = await Axios.post(`/api/${type}`, {
username: state.username,
password: state.password,
});
console.log(response);
dispatch({ type: ACTIONS.REQUEST, value: false });
} catch (e) {
console.log(e);
dispatch({ type: ACTIONS.REQUEST, value: false });
}
}
sendRequest();
return () => ourRequest.cancel();
}, [state.requestInFlight]);
return (
<Form
onSubmit={(e) => {
e.preventDefault();
dispatch({ type: ACTIONS.REQUEST, value: true });
}}
>
<Form.Group controlId="formBasicEmail">
<Form.Label className="text-muted">Username</Form.Label>
<Form.Control
type="text"
placeholder="Enter Username"
onChange={(e) =>
dispatch({ type: ACTIONS.UPDATE_USERNAME, value: e.target.value })
}
/>
</Form.Group>
<Form.Group controlId="formBasicPassword">
<Form.Label className="text-muted">Password</Form.Label>
<Form.Control
type="password"
placeholder="Password"
onChange={(e) =>
dispatch({ type: ACTIONS.UPDATE_PASSWORD, value: e.target.value })
}
/>
</Form.Group>
<Button variant="primary" type="submit">
{type}
</Button>
</Form>
);
}
export default FormComponent;
[1]: https://i.stack.imgur.com/jD0sO.png
[2]: https://reactjs.org/docs/hooks-reference.html#usereducer
Your reducer setup is wrong, its returning undefined once it runs initially. You need to return your updated object instead of undefined.
function reducer(draft, { type, value }) {
switch (type) {
case ACTIONS.UPDATE_USERNAME:
return {...draft, username: value };
case ACTIONS.UPDATE_PASSWORD:
return {...draft, password: value };
case ACTIONS.REQUEST:
return {...draft, requestInFlight: value };
default:
return draft;
}
}
The first answer is the correct answer but there is something I need to point out from your implementation.
Reducer functions have to be pure!
why? I recommend reading this article: https://www.freecodecamp.org/news/why-redux-needs-reducers-to-be-pure-functions-d438c58ae468/

asynchronous function test onChange event fails in enzyme and jest

I built a form with formik + material-ui in React app.
and want to test input onChange event with Jest, enzyme and sinon.
I used setTimeout() since Formik's handlers are asynchronous and enzyme's change event is synchronous.
problem
testing 'if the value is displayed on input change' fails.
const input = wrapper.find('#username');
input.simulate('change', { target: { name: 'username', value: 'y' }
setTimeout(() => {
expect(mockChange.calledOnce).toBe(true); // test is passed.
expect(input.props().value).toEqual('y'); // Expected value to equal: "y" , Received: ""
done();
}, 1000);
loginContainer
...
render() {
const values = { username: '', password: '' };
return (
<React.Fragment>
<Formik
initialValues={values}
render={props => <Form {...props} />}
onSubmit={this.handleUserLogin}
validationSchema={loginValidation}
/>
</React.Fragment>
);
}
...
loginForm
import React from 'react';
import TextField from '#material-ui/core/TextField';
...
const styles = theme => ({ });
const Form = props => {
const {
values: { username, password },
errors,
touched,
handleChange,
handleSubmit,
isSubmitting,
handleBlur,
classes,
} = props;
return (
<div className="login-container" data-test="loginformComponent">
<form onSubmit={handleSubmit} className="flex flex-column-m items-center">
<TextField
id="username"
value={username || ''}
onChange={handleChange}
...
/>
<TextField
id="password"
value={password || ''}
onChange={handleChange}
...
/>
...
</form>
</div>
);
};
export const Unwrapped = Form;
export default withStyles(styles)(Form);
loginForm.test
import React, { shallow, sinon } from '../../__tests__/setupTests';
import { Unwrapped as UnwrappedLoginForm } from './loginForm';
const mockBlur = jest.fn();
const mockChange = sinon.spy();
const mockSubmit = sinon.spy();
const setUp = (props = {}) => {
const component = shallow(<UnwrappedLoginForm {...props} />);
return component;
};
describe('Login Form Component', () => {
let wrapper;
beforeEach(() => {
const props = {
values: { username: '', password: '' },
errors: { username: false, password: false },
touched: { username: false, password: false },
handleChange: mockChange,
handleSubmit: mockSubmit,
isSubmitting: false,
handleBlur: mockBlur,
classes: {
textField: '',
},
};
wrapper = setUp(props);
});
describe('When the input value is inserted', () => {
it('renders new username value', done => {
const input = wrapper.find('#username');
input.simulate('change', { target: { name: 'username', value: 'y' } });
setTimeout(() => {
wrapper.update();
expect(mockChange.calledOnce).toEqual(true);
done();
}, 1000);
});
});
});
Try the following:
const waitForNextTick = process.nextTick
waitForNextTick(() => {
expect(mockChange.calledOnce).toBe(true); // test is passed.
expect(input.props().value).toEqual('y'); // Expected value to equal: "y" , Received: ""
done();
});
From the code you have provided, I don't think the value of the input is going to be updated.
You are triggering the change event on TextField component. What this triggers is the onChange callback for the input, which in turn executes the handleChange prop of your UnwrappedLoginForm component. But this does not change the input value per se.

React. How to populate the form after the login is completed

I have two react components(SignupDetails.js, BasicInformation.js). SignupDetails is obviously responsible to signup the user, it will get the user information from the form and submit it to the server through axios.
On the server side(backend), if the user already exist, the server will then collect the remain information, such as first name, middle name, etc and then send it back to be collected on the client side.
Back to the client side, now the remain user information which has been returned is then stored in the central store using the redux-reducers and the page is then "redirected" to BasicInformation.js
Now on the BasicInformation.js, mapStateToPros is then executed so I will do have access to the information that has been stored on the central store but then it becomes the problem: I am struggling to show the remain information. This sounds pretty simple but I tried many things on the componentDidUpdate and on the render method but without being successful.
Please find the code below and let me know if you any ideas.
import React, {Component} from 'react';
import classes from './SignUp.module.css';
import {connect} from 'react-redux'
import * as actions from '../../store/actions/index';
import Spinner from '../../components/UI/Spinner/Spinner'
class SignupDetails extends Component {
constructor(props) {
super(props)
this.state = {
email: '',
password: ''
};
this.handleInputChange = this.handleInputChange.bind(this);
}
handleInputChange(event) {
const target = event.target;
const value = target.type === 'checkbox' ? target.checked : target.value;
const name = target.name;
this.setState({
[name]: value
});
}
postDataHandler = () => {
const data = {
username: this.state.email,
email: this.state.email,
password: this.state.password
};
this.props.onSignupDetails(data);
}
componentDidMount() {
this.props.history.push({pathname: '/signup_details/'})
}
componentDidUpdate() {
if (this.props.signup_details_success)
this.props.history.push({pathname: '/basic_information/'})
}
render() {
let errorMessage = null;
if (this.props.error) {
errorMessage = (
<p>{this.props.signup_details_response}</p>
);
}
return (
<div>
<Spinner show={this.props.loading}/>
<div className={classes.SignUpForm}>
{errorMessage}
<h3>Take your first step.</h3>
<div>
<input
key="email"
name="email"
value={this.state.email}
onChange={this.handleInputChange}/>
</div>
<div>
<input
key="password"
name="password"
value={this.state.password}
onChange={this.handleInputChange}/>
</div>
<button className={classes.OkButton} onClick={this.postDataHandler}>Next</button>
</div>
</div>
);
}
}
const mapStateToProps = state => {
return {
signup_details: state.signup.signup_details,
signup_details_success: state.signup.signup_details_success,
signup_details_response: state.signup.signup_details_response,
loading: state.signup.loading,
error: state.signup.error
};
};
const mapDispatchToProps = dispatch => {
return {
onSignupDetails: (signup_details) => dispatch(actions.signupDetails(signup_details))
};
};
export default connect(mapStateToProps, mapDispatchToProps)(SignupDetails);
-----
import React, {Component} from 'react';
import classes from './SignUp.module.css';
import {connect} from 'react-redux'
import * as actions from '../../store/actions/index';
import Spinner from '../../components/UI/Spinner/Spinner'
class BasicInformation extends Component {
constructor(props) {
super(props)
this.state = {
first_name: '',
middle_name: '',
last_name: '',
mobile_number: '',
fund_balance: ''
}
this.handleInputChange = this.handleInputChange.bind(this);
}
handleInputChange(event) {
const target = event.target;
const value = target.type === 'checkbox' ? target.checked : target.value;
const name = target.name;
this.setState({
[name]: value
});
}
postDataHandler = () => {
const data = {
username: this.state.email,
email: this.state.email,
first_name: this.state.first_name,
middle_name: this.state.middle_name,
last_name: this.state.last_name,
mobile_number: this.state.mobile_number,
sfunds: [{balance: this.state.fund_balance}]
};
this.props.onSignupBasicInformation(data);
}
componentDidUpdate() {
if (this.props.signup_basic_information_success)
this.props.history.push({pathname: '/personal_information/'})
}
render() {
let errorMessage = null;
if (this.props.error) {
errorMessage = (
<p>{this.props.signup_basic_information_response}</p>
);
}
return (
<div>
<Spinner show={this.props.loading}/>
<div className={classes.SignUpForm}>
{errorMessage}
<h3>First we need some basic information</h3>
<div><input
key="first_name"
name="first_name"
value={this.state.first_name}
onChange={this.handleInputChange}/></div>
<div><input
key="middle_name"
name="middle_name"
value={this.state.middle_name}
onChange={this.handleInputChange}/></div>
<div><input
key="last_name"
name="last_name"
value={this.state.last_name}
onChange={this.handleInputChange}/></div>
<div><input
key="mobile_number"
name="mobile_number"
value={this.state.mobile_number}
onChange={this.handleInputChange}/></div>
<div><input
key="fund_balance"
name="fund_balance"
value={this.state.fund_balance}
onChange={this.handleInputChange}/></div>
<button className={classes.OkButton} onClick={this.postDataHandler}>Next</button>
</div>
</div>
);
}
}
const mapStateToProps = state => {
return {
signup_details_success: state.signup.signup_details_success,
signup_details_response: state.signup.signup_details_response,
signup_basic_information: state.signup.signup_basic_information,
signup_basic_information_success: state.signup.signup_basic_information_success,
signup_basic_information_response: state.signup.signup_basic_information_response,
loading: state.signup.loading,
error: state.signup.error
};
};
const mapDispatchToProps = dispatch => {
return {
onSignupBasicInformation: (basic_information) => dispatch(actions.signupBasicInformation(basic_information))
};
};
export default connect(mapStateToProps, mapDispatchToProps)(BasicInformation);
In case someone wonder, I managed to solve this problem through componentDidMount to set the local state.
componentDidMount(){
if(this.props.smsf_member_details) {
this.setState({
first_name: this.props.smsf_member_details.first_name,
last_name: this.props.smsf_member_details.last_name,
middle_name: this.props.smsf_member_details.middle_name,
});
}
}

Set State using query component React apollo

I have used same form to create and update account(module). Create is working fine but in update mode I am not able to set form field value using Set State methods. I have used query component on render methods and setstate not working on rendor method.
import { Mutation } from "react-apollo";
import { Query } from "react-apollo";
import gql from "graphql-tag";
import React, { Component } from "react";
import Router from "next/router";
import Joi from "joi-browser";
const CREATE_ACCOUNT = gql`
mutation CreateAccount(
$name: String
$phone_office: String
$website: String
) {
createAccount(name: $name, phone_office: $phone_office, website:
$website) {
name
phone_office
website
}
}
`;
export const allAccountbyidQuery = gql`
query account($id: String) {
account(id: $id) {
id
name
phone_office
website
}
};
const schema = {
name: Joi.string()
.required()
.error(errors => {
return {
message: "Name is required!"
};
}),
phone_office: Joi.string()
.required()
.error(errors => {
return {
message: "Phone Number is required!"
};
}),
website: Joi.string()
.required()
.error(errors => {
return {
message: "Website is required!"
};
})
};
Main class component
class CreateAccountModule extends React.Component {
static async getInitialProps({ query }) {
const { id } = query;
return { id };
}
constructor(props) {
super();
this.state = {
isFirstRender: true,
name: "",
phone_office: "",
website: ""
};
}
handleChange = event => {
console.log("hello");
const { name, value } = event.target;
this.setState({ [name]: value });
};
validate(name, phone_office, website) {
let errors = "";
const result = Joi.validate(
{
name: name,
phone_office: phone_office,
website: website
},
schema
);
if (result.error) {
errors = result.error.details[0].message;
}
return errors;
}
setName = name => {
if (this.state.isFirstRender) {
this.setState({ name, isFirstRender: false });
}
};
render() {
let input;
const { errors } = this.state;
console.log(this.props);
const allAccountbyidQueryVars = {
id: this.props.id
};
//console.log(allAccountbyidQueryVars);
return (
<Query
query={allAccountbyidQuery}
variables={allAccountbyidQueryVars}
onCompleted={data => this.setName(data.account.name)}
>
{({ data, loading, error }) => {
<CreateAccountModule account={data.account} />;
return (
<Mutation mutation={CREATE_ACCOUNT}>
{(createAccount, { loading, error }) => (
<div>
<form
onSubmit={e => {
e.preventDefault();
const errors = this.validate(
e.target.name.value,
e.target.phone_office.value,
e.target.website.value
);
if (errors) {
this.setState({ errors });
return;
}
if (!errors) {
let accountres = createAccount({
variables: {
name: e.target.name.value,
phone_office: e.target.phone_office.value,
website: e.target.website.value
}
}).then(() => Router.push("/"));
input.value = "";
}
}}
>
{errors && <p>{errors}</p>}
<input
type="text"
name="name"
id="name"
placeholder="Name"
value={this.state.name}
onChange={this.handleChange}
/>
<input
name="phone_office"
id="phone_office"
placeholder="Phone Number"
//value={data.account.phone_office}
//value="123456"
onChange={this.handleChange}
/>
<input
name="website"
id="website"
placeholder="Website"
//value={data.account.website}
onChange={this.handleChange}
/>
<button type="submit">Add Account</button>
<button type="button">Cancel</button>
</form>
{loading && <p>Loading...</p>}
{error && <p>Error :( Please try again</p>}
</div>
)}
</Mutation>
);
}}
</Query>
);
}
}
export default CreateAccountModule;
`
I have tried with props but get props data in apollo state. anyone please suggest possible solution to fix this issue.

Resources