can't switch status value from 0 to 1 after calling function angular - rest

I am working on a frontend application with Angular 5 and using rest api from backend. Actually, I am developing admin platforme and I have two web pages, one for displaying list of customers and each one has list of feedbacks and one other get you to specific feedback details.
The feedback details display these properties: account, feedback itself and the loyalty point if existed.
There is two ways, if a feedback has its loyalty point then the feedback details will show details with loyalty point value else it will show empty input for this property and if the input is successful, it will return to main list with changed value of status of feedback from false to true.
I am using rest api and for this operation I successfully tested the API:
API: PATCH /Feedbacks/:id
Here is my code:
account.service.ts:
#Injectable()
export class AccountService {
constructor(private http: Http) {}
headers: Headers = new Headers({ 'Content-Type': 'application/json' });
options: RequestOptionsArgs = new RequestOptions({headers: this.headers});
// API: PATCH /Feedbacks/:id
updateStatus(feedback: Feedback) {
let url = "http://localhost:3000/api/Feedbacks";
return this.http.patch(url + feedback.id, feedback, this.options)
.map(res => res.json())
.catch(err => {
return Observable.throw(err)
});
}
}
component.html:
<form *ngIf="feedback">
<div class="form-group">
<label for="InputAccount">Account</label>
<input type="text" class="form-control" id="InputAccount" value="{{feedback.account}}">
</div>
<div class="form-group">
<label for="InputFeedback">Feedback</label>
<textarea class="form-control" id="InputFeedback" rows="3" placeholder="Feedback">{{feedback.feedback}}</textarea>
</div>
<div class="form-group">
<label for="InputLP">LP</label>
<input type="text" class="form-control" id="InputLP" placeholder="LP" [(ngModel)]="account.lp" name="lp">
</div>
<div class="form-group" *ngIf="!edited; else showBack">
<button (click)="addLP(account,feedback)" class="btn btn-primary" data-dismiss="alert">Add LP</button>
</div>
</form>
component.ts:
#Component({
selector: 'app-add',
templateUrl: './add.component.html',
styleUrls: ['./add.component.scss']
})
export class AddComponent implements OnInit {
feedback = {};
account = {};
edited:boolean;
status: boolean;
constructor(private route: ActivatedRoute, private accountService: AccountService,
private router: Router) { }
ngOnInit() {
this.route.paramMap
.switchMap((params: ParamMap) =>
this.accountService.getFeedback(+params.get('idF')))
.subscribe(feedback => this.feedback = feedback);
this.route.paramMap
.switchMap((params: ParamMap) =>
this.accountService.getAccount(params.get('idC')))
.subscribe(account => this.account = account);
}
addLP(account:Account,feedback:Feedback){
this.accountService.updateAccount(account)
.subscribe(res => {
this.account = res as Account;
console.log(res);
if (account.lp == null){
console.log(res);
this.edited = false;
} else {
this.edited = true;
this.accountService.updateStatus(feedback)
.subscribe(res => {
feedback.status = true;
this.feedback = res as Feedback;
console.log(this.feedback);
}, err => {
console.log(err);
});
}
}, err => {
console.log(err);
});
}
back() {
this.router.navigate(['list']);
}
}
the feedback property:
public id?: number,
public feedback?: string,
public account?: string,
public status?: boolean
Where the account is a foreign key to account table:
public account?: string,
public lp?: string
When I try to switch status value automatically from false to true, the console log will return:
PATCH http://localhost:3000/api/Feedbacks2 404 (Not Found)
Any help would be appreciated! I really need to solve it. Thanks

I modified the code in account.service.ts:
updateStatus(feedback: Feedback) {
let url = "http://localhost:3000/api/Feedbacks";
var body = {status: true};
return this.http.patch(url +"/"+ feedback.id, body, this.options)
.map(res => res.json())
.catch(err => {
return Observable.throw(err)
});
}
And it worked !

Related

updating form ion-select in Ionic

I want to perform an update in an ion-select but I can't. My level of programming is very low and there are still many things that I don't understand.
The options are read from a table ('categories') that has two fields ('id', 'name') through the getAllCategories() method, but I can't get the value of the 'name' field that is already assigned to it to be displayed
I do a search for the category with its corresponding Id with the getCategory(1) method (I have put a 1, because I don't know how to search through a variable) but it does not appear selected (where it says 'Select Category') despite I think I'm sending the data correctly, because it appears in the console.log
update-recipe.page.html
<ion-item lines="full">
<ion-select id="category" name="category" placeHolder="Select Category" (ionChange)="ObtenerCategoryId($event)">
<ion-select-option *ngFor="let category of categories" value="{{category.id}}">{{category.name}}</ion-select-option>
</ion-select>
</ion-item>
<form [formGroup]="updateRecipeForm" (ngSubmit)="onSubmit()" novalidate>
<ion-item lines="full">
<ion-label position="floating">Tittle</ion-label>
<ion-input formControlName="tittle" type="text" required></ion-input>
</ion-item>
<!-- <span class="error ion-padding" *ngIf="isSubmitted && errorControl.name.errors?.required">Tittle is required.</span> -->
<ion-item lines="full">
<ion-label position="floating">Description</ion-label>
<ion-input formControlName="description" type="text" required></ion-input>
</ion-item>
<!-- <span class="error ion-padding" *ngIf="isSubmitted && errorControl.description.errors?.required">Description is required.</span> -->
<ion-row>
<ion-col>
<ion-button type="submit" color="primary" expand="block">Update</ion-button>
</ion-col>
</ion-row>
</form>
update-crecipe.page.ts
export class Recipe {
id: number;
tittle: string;
description: string;
filename: string;
userId: number;
categoryId: number;
}
#Component({
selector: "app-update-recipe",
templateUrl: "./update-recipe.page.html",
styleUrls: ["./update-recipe.page.scss"],
})
export class UpdateRecipePage implements OnInit {
categories: any =[];
categoryId: any;
updateRecipeForm: FormGroup;
isSubmitted = false;
id: any;
capturedPhoto = '';
// eslint-disable-next-line #typescript-eslint/no-inferrable-types
imageSaved: string = '';
constructor(
private recipeService: RecipeService,
private categoryService: CategoryService,
private activatedRoute: ActivatedRoute,
private formBuilder: FormBuilder,
private router: Router,
private photoService: PhotoService,
private storage: Storage
) {
this.id = this.activatedRoute.snapshot.paramMap.get('id');
}
ionViewWillEnter(){
this.findRecipe(this.id);
this.updateRecipeForm = this.formBuilder.group({
tittle: [''],
description: [''],
filename: [''],
categoryId: ['']
});
this.capturedPhoto = '';
}
ngOnInit() {
this.findRecipe(this.id);
this.updateRecipeForm = this.formBuilder.group({
tittle: [''],
description: [''],
filename: [''],
categoryId: ['']
},
);
this.capturedPhoto = '';
// this.updateRecipeForm.reset();
this.getCategory(1);
this.getAllCategories();
}
async findRecipe(id) {
let token = await this.storage.get("token");
this.recipeService.getRecipe(this.id, token).subscribe(async data => {
this.imageSaved = data['filename'];
this.updateRecipeForm.setValue({
tittle: data['tittle'],
description: data['description'],
filename: data['filename'],
categoryId: data ['categoryId']
});
});
}
async ObtenerCategoryId(e){
console.log("valor obtenido"+e.detail.value);
let categoryId = await this.storage.set("categoryId_st", e.detail.value);
}
async getCategory(id) {
let token = await this.storage.get("token");
this.categoryService.getCategory(id, token).subscribe(async res => {
console.log(res);
this.categories = res;
}, error => {
console.log(error);
console.log("User not authenticated. Please log in");
this.router.navigateByUrl("/home");
});
}
async getAllCategories() {
let token = await this.storage.get("token");
this.categoryService.getCategories(token).subscribe(async res => {
console.log(res);
this.categories = res;
}, error => {
console.log(error);
console.log("User not authenticated. Please log in");
this.router.navigateByUrl("/home");
});
}
async onSubmit() {
this.isSubmitted = true;
if (!this.updateRecipeForm.valid) {
return false;
} else {
let blob = null;
if (this.capturedPhoto !== "") {
const response = await fetch(this.capturedPhoto);
blob = await response.blob();
}
(
await this.recipeService
.updateRecipe(this.id, this.updateRecipeForm.value, blob, this.getCategory(this.id)))
.subscribe(data => {
console.log('¡Photo sent!');
this.updateRecipeForm.reset();
this.router.navigate(['/you-are-logged-in']);
});
}
}
There are many typos in the code.
Secondly, you need to read the documentation if you're new. The documentation provides your answer: https://ionicframework.com/docs/api/select#object-value-references

Function Query.where() requires a valid third argument, but it was undefined when trying to view the page

I'm trying to implement rating system in my shopping app, but received error console when trying to open the page.
The error on console are:
Function Query.where() requires a valid third argument, but it was undefined. - it points to:
this.stars = this.starService.getProductStars(this.movieId)
AND
const starsRef = this.afs.collection('stars', ref => ref.where('movieId', '==', movieId));
Below is my code:
rating.page.html: (where I put my 2 of components which are TestRate and Star-Review)
<ion-content>
<app-testrate></app-testrate>
<app-star-review-component></app-star-review-component>
</ion-content>
testrate.component.html:
<div *ngIf="movie | async as m">
<h1>
{{m.title}}
</h1>
<img [src]="m.image" width="100px">
<p>
{{m.plot}}
</p>
<star-review [movieId]="movieId" [userId]="userId"></star-review>
</div>
testrate.component.ts:
export class TestrateComponent implements OnInit {
userDoc: AngularFirestoreDocument<any>;
movieDoc: AngularFirestoreDocument<any>;
user: Observable<any>;
movie: Observable<any>;
constructor(private afs: AngularFirestore) { }
ngOnInit() {
this.userDoc = this.afs.doc('users/test-user-3')
this.movieDoc = this.afs.doc('movies/battlefield-earth')
this.movie = this.movieDoc.valueChanges()
this.user = this.userDoc.valueChanges()
}
get movieId() {
return this.movieDoc.ref.id
}
get userId() {
return this.userDoc.ref.id
}
}
star-review.component.html:
<h3>Average Rating</h3>
{{ avgRating | async }}
<h3>Reviews</h3>
<div *ngFor="let star of stars | async">
{{ star.userId }} gave {{ star.movieId }} {{ star.value }} stars
</div>
<h3>Post your Review</h3>
<fieldset class="rating">
<ng-container *ngFor="let num of [5, 4, 3, 2, 1]">
full star
<input (click)="starHandler(num)"
[id]="'star'+num"
[value]="num-0.5"
name="rating"
type="radio" />
<label class="full" [for]="'star'+num"></label>
half star
<input (click)="starHandler(num-0.5)"
[value]="num-0.5"
[id]="'halfstar'+num"
name="rating"
type="radio" />
<label class="half" [for]="'halfstar'+num"></label>
</ng-container>
</fieldset>
star-review.component.ts:
export class StarReviewComponentComponent implements OnInit {
#Input() userId;
#Input() movieId;
stars: Observable<any>;
avgRating: Observable<any>;
constructor(private starService: StarService) { }
ngOnInit() {
this.stars = this.starService.getProductStars(this.movieId)
this.avgRating = this.stars.pipe(map(arr => {
const ratings = arr.map(v => v.value)
return ratings.length ? ratings.reduce((total, val) => total + val) / arr.length : 'not reviewed'
}))
}
starHandler(value) {
this.starService.setStar(this.userId, this.movieId, value)
}
}
star.service.ts:
export class StarService {
constructor(private afs: AngularFirestore) { }
// Star reviews that belong to a user
getUserStars(userId) {
const starsRef = this.afs.collection('stars', ref => ref.where('userId', '==', userId));
return starsRef.valueChanges();
}
// Get all stars that belog to a Product
getProductStars(movieId) {
const starsRef = this.afs.collection('stars', ref => ref.where('movieId', '==', movieId));
return starsRef.valueChanges();
}
// Create or update star
setStar(userId, movieId, value) {
// Star document data
const star: Star = { userId, movieId, value };
// Custom doc ID for relationship
const starPath = `stars/${star.userId}_${star.movieId}`;
// Set the data, return the promise
return this.afs.doc(starPath).set(star)
}
}

Angular 5 - Updating Model from Form

i'm new to Angular 5 and i'm trying to make a CRUD.
i'm struggling with the "update" part.
what i'd want to do is, in my form, getting back the data of the Model to fill the input text with, then, when i click on the update button, updating the all model.
I tried so many thing from tuts and forums that i'm completly lost now. So here is what i have.
html :
<form [formGroup]="policyForm" (ngSubmit)="update()">
<mat-form-field>
<input formControlName="policyName">
</mat-form-field>
... Many other inputs
<button type="submit" color="primary">Update</button>
</form>
component :
export class PolicyUpdateComponent implements OnInit {
policyModel: PolicyModel;
policyId = +this.route.snapshot.paramMap.get('id');
policyForm: FormGroup;
formBuilder: FormBuilder;
constructor(
private policyService: PolicyService,
private route: ActivatedRoute,
private router: Router,
private fb: FormBuilder
) {
this.policyService.get(this.policyId)
.subscribe(policy => this.policyModel = policy);
}
ngOnInit() {
this.createForm();
}
createForm() {
this.policyForm = this.fb.group({
policyName: [this.policyModel.name, Validators.required]
});
}
update(id: number) {
id = this.policyId;
this.policyModel = <PolicyModel>this.policyForm.value;
this.policyService.update(id, this.policyModel).subscribe(res => {
this.router.navigate(['/policies', id, 'get']);
}, (e) => {
console.log(e);
}
);
}
}
service :
/**
* Update a policy with new parameters
* #param pm PolicyModel
*/
update(id: number, pm: PolicyModel): Observable<any> {
return this.http.put<PolicyModel>(`${environment.baseApiUrl}/${environment.apiVersion}/policies/${id}`, {pm});
}
any help would be nice.. thanks guys!
Change the code according to this.
<form [formGroup]="policyForm" >
<mat-form-field>
<input formControlName="policyName">
</mat-form-field>
<button color="primary" (click)="update()">Update</button>
</form>
Add subscription to detect form changes.
ngOnInit() {
this.createForm();
this.policyForm.valueChanges.subscribe(
(data) => {
if (JSON.stringify(data) !== JSON.stringify({})) {
this.policyModel.name = data.policyName;
}
});
}
createForm() {
this.policyForm = this.fb.group({
policyName: [this.policyModel.name]
});
}
update(id) {
this.policyModel.id = id;
id = this.policyId;
this.policyService.update(id, this.policyModel)//.subscribe(res => {
this.router.navigate(['/policies', id, 'get']);
}, (e) => {
console.log(e);
}
);
}
Sample code : https://stackblitz.com/edit/angular-wwt91u

ReactJS Semantic ui - Cannot type into form when value attribute exists

I am following a ReactJS tutorial to set up a login form. Semantic ui is used and imported. The email and password are passed into the value attribute inside the form. When this happens, I cannot type anything into the form. As soon as I remove it, I can type information in but I assume it won't get passed into anywhere.
Cannot seem to find this issues anywhere else. Has anyone experienced this issue before?
import React from 'react';
import PropTypes from 'prop-types';
import { Form, Button } from 'semantic-ui-react';
import Validator from 'validator';
import InlineError from '../messages/InlineError';
class LoginForm extends React.Component {
state = {
data: {
email: "",
password: ""
},
loading: false,
errors: {}
};
//... is called spread
onChange = e => this.setState({
data: {...this.state.data, [e.target.name]: e.target.value }
});
//() means function takes no params
onSubmit = () => {
const errors = this.validate(this.state.data);
this.setState({errors}); //if there are errors, display them
if(Object.keys(errors).length === 0){
this.props.submit(this.state.data);
}
};
validate = (data) => {
const errors = {};
if(!Validator.isEmail(data.email))
errors.email = "Invalid email";
if(!data.password)
errors.password = "Can't be blank";
return errors;
};
render() {
const { data, errors } = this.state; // import variables into html
return (
<div>
<Form onSubmit={ this.onSubmit }>
<Form.Field error={!!errors.email}>
<label htmlFor="email">Email</label>
<input type="email"
id="email"
placeholder="example#abc.com"
value={ data.email }
onChange={ this.onChange }/>
{errors.email && <InlineError text={errors.email}/>}
</Form.Field>
<Form.Field error={!!errors.email}>
<label htmlFor="password">Password</label>
<input type="password"
id="password"
value={ data.password }
onChange={this.onChange}/>
{errors.password && <InlineError text={errors.password}/>}
</Form.Field>
<Button primary>Login</Button>
</Form>
</div>
);
}
}
LoginForm.propTypes = {
submit: PropTypes.func.isRequired
};
export default LoginForm;
tutorial: https://www.youtube.com/watch?v=NO2DaxhoWHk&t=879s
onChange = e => this.setState({
data: {...this.state.data, [e.target.name]: e.target.value }
});
This function is setting the state to a variable that shares the name of your input field. Hence e.target.name. But your input fields do not have a name attribute.
You can fix that with:
import React from 'react';
import PropTypes from 'prop-types';
import { Form, Button } from 'semantic-ui-react';
import Validator from 'validator';
import InlineError from '../messages/InlineError';
class LoginForm extends React.Component {
state = {
data: {
email: "",
password: ""
},
loading: false,
errors: {}
};
//... is called spread
onChange = e => this.setState({
data: {...this.state.data, [e.target.name]: e.target.value }
});
//() means function takes no params
onSubmit = () => {
const errors = this.validate(this.state.data);
this.setState({errors}); //if there are errors, display them
if(Object.keys(errors).length === 0){
this.props.submit(this.state.data);
}
};
validate = (data) => {
const errors = {};
if(!Validator.isEmail(data.email))
errors.email = "Invalid email";
if(!data.password)
errors.password = "Can't be blank";
return errors;
};
render() {
const { data, errors } = this.state; // import variables into html
return (
<div>
<Form onSubmit={ this.onSubmit }>
<Form.Field error={!!errors.email}>
<label htmlFor="email">Email</label>
<input type="email"
id="email"
name="email"
placeholder="example#abc.com"
value={ data.email }
onChange={ this.onChange }/>
{errors.email && <InlineError text={errors.email}/>}
</Form.Field>
<Form.Field error={!!errors.email}>
<label htmlFor="password">Password</label>
<input type="password"
id="password"
name="password"
value={ data.password }
onChange={this.onChange}/>
{errors.password && <InlineError text={errors.password}/>}
</Form.Field>
<Button primary>Login</Button>
</Form>
</div>
);
}
}
LoginForm.propTypes = {
submit: PropTypes.func.isRequired
};
export default LoginForm;

React/Redux clear form elements values after submit

I have problems with clearing values from input and select form elements in react form after successful submit through axios library. Just want to mention that i do not use redux-form.
I don't know if I am on the right track here, this is my workflow by far: I wrote a form with react-bootstrap, give every input and select value through props and I access and update the state through these props. I have wrote actions and reducers for updating input values, and one action is dispatched in my component, but the second action and the reducer that is supposed to clear values after submit doesn't work as expected. This is the main problem, I'm not sure if I dispatch FORM_RESET action form in the right place, because I call it in the action that is responsible for posting data to server, and on success callback I dispatch FORM_RESET.
Below is the code relevant for this problem.
/* actionRegister.js */
let _registerUserFailure = (payload) => {
return {
type: types.SAVE_USER_FAILURE,
payload
};
};
let _registerUserSuccess = (payload) => {
return {
type: types.SAVE_USER_SUCCESS,
payload,
is_Active: 0,
isLoading:true
};
};
let _hideNotification = (payload) => {
return {
type: types.HIDE_NOTIFICATION,
payload: ''
};
};
//asynchronous helpers
export function registerUser({ //use redux-thunk for asynchronous dispatch
timezone,
password,
passwordConfirmation,
email,
name
}) {
return dispatch => {
axios.all([axios.post('/auth/signup', {
timezone,
password,
passwordConfirmation,
email,
name,
is_Active: 0
})
// axios.post('/send', {email})
])
.then(axios.spread(res => {
dispatch(_registerUserSuccess(res.data.message));
dispatch(formReset()); //here I dispatch clearing form data
setTimeout(() => {
dispatch(_hideNotification(res.data.message));
}, 10000);
}))
.catch(res => {
dispatch(_registerUserFailure(res.data.message)); //BE validation and passport error message
setTimeout(() => {
dispatch(_hideNotification(res.data.message));
}, 10000);
});
};
}
/* actionForm.js */
//synchronous action creators
export function formUpdate(name, value) {
return {
type: types.FORM_UPDATE_VALUE,
name, //shorthand from name:name introduced in ES2016
value
};
}
export function formReset() {
return {
type: types.FORM_RESET
};
}
/* reducerRegister.js */
const INITIAL_STATE = {
error:{},
is_Active:false,
isLoading:false
};
const reducerSignup = (state = INITIAL_STATE , action) => {
switch(action.type) {
case types.SAVE_USER_SUCCESS:
return { ...state, is_Active:false, isLoading: true, error: { register: action.payload }};
case types.SAVE_USER_FAILURE:
return { ...state, error: { register: action.payload }};
case types.HIDE_NOTIFICATION:
return { ...state , error:{} };
}
return state;
};
export default reducerSignup;
/* reducerForm.js */
const INITIAL_STATE = {
values: {}
};
const reducerUpdate = (state = INITIAL_STATE, action) => {
switch (action.type) {
case types.FORM_UPDATE_VALUE:
return Object.assign({}, state, {
values: Object.assign({}, state.values, {
[action.name]: action.value,
})
});
case types.FORM_RESET:
return INITIAL_STATE;
//here I need isLoading value from reducerRegister.js
}
return state;
};
export default reducerUpdate;
/* SignupForm.js */
import React, {Component} from 'react';
import {reduxForm} from 'redux-form';
import {connect} from 'react-redux';
import map from 'lodash/map';
import timezones from '../../data/timezones';
import styles from '../formElements/formElements.scss';
import {registerUser} from '../../actions/actionRegister';
import {formUpdate} from '../../actions/actionForm';
import FieldGroup from '../formElements/FieldGroup';
import { Form, FormControl, Col, Checkbox, Button, FormGroup } from 'react-bootstrap';
// {... props} passing large number of props wrap in object with spread notation
class SignupForm extends Component { //if component have state it needs to be class
constructor(props) {
super(props);
this.state = {
errors: { //this errors are irrelevant for now
name:'',
email: '',
password: '',
passwordConfirmation:'',
timezone:''
},
};
}
onChange = (event, index, value) => {
this.props.onChange(event.target.name, event.target.value);
};
onSave = (event) => {
event.preventDefault();
this.props.onSave(this.props.values);
}
render() {
let isLoading = this.props.isLoading;
return (
// this.props.handleSubmit is created by reduxForm()
// if the form is valid, it will call this.props.onSubmit
<Form onSubmit={this.onSave} horizontal>
<FieldGroup
id="formControlsName"
type="text"
label="Name"
name="name"
placeholder="Enter Name"
value={this.props.values[name]}
onChange={this.onChange}
help={this.state.errors.name}
/>
<FieldGroup
id="formControlsEmail"
type="text"
label="Email"
name="email"
placeholder="Enter Email"
value={this.props.values[name]}
onChange={this.onChange}
help={this.state.errors.email}
/>
<FieldGroup
id="formControlsPassword"
type="password"
label="Password"
name="password"
placeholder="Enter Password"
value={this.props.values[name]}
onChange={this.onChange}
help={this.state.errors.password}
/>
<FieldGroup
id="formControlsPasswordConfirmation"
type="password"
label="Password Confirmation"
name="passwordConfirmation"
placeholder="Enter Password"
value={this.props.values[name]}
onChange={this.onChange}
help={this.state.errors.passwordConfirmation}
/>
<FieldGroup
id="formControlsTimezone"
label="Time Zone"
name="timezone"
placeholder="Select Time Zone"
componentClass="select"
defaultValue="Select Your Timezone"
value={this.props.values[name]}
onChange={this.onChange}
help={this.state.errors.timezone}
>
<option value="Select Your Timezone">Select Your Timezone</option>
{
map(timezones, (key, value) =>
<option key={key} value={key}>{value}</option>)
}
</FieldGroup>
<FormGroup>
<Col smOffset={4} sm={8}>
<Checkbox>Remember me</Checkbox>
</Col>
</FormGroup>
<FormGroup>
<Col smOffset={4} sm={8}>
<Button type="submit" disabled={isLoading}
onClick={!isLoading ? isLoading : null}
>
{ isLoading ? 'Creating...' : 'Create New Account'}
</Button>
</Col>
</FormGroup>
{this.props.errorMessage && this.props.errorMessage.register &&
<div className="error-container">{this.props.errorMessage.register}</div>}
</Form>
//this.setState({ disabled: true });
//this.props.errorMessage.register == this.props = {errorMessage :{ register: ''}}
);
}
}
function mapStateToProps(state) {
return {
errorMessage: state.signup.error,
isLoading: state.signup.isLoading,
values: state.form.values
};
}
function mapDispatchToProps(dispatch) {
return {
onSave: (values) => dispatch(registerUser(values)),
onChange: (name, value) => dispatch(formUpdate(name, value))
};
}
export default connect(mapStateToProps, mapDispatchToProps)(SignupForm)
;
There is no need to use redux-form :-) You're on the right path and you're calling FORM_RESET action in the right place.
Couple of things:
are you sure you are importing formReset in actionRegister.js?
in reducerForm I would suggest to still return new state here:
case types.FORM_RESET:
return { ...INITIAL_STATE }; // or Object.assign({}, INITIAL_STATE)
And btw. why are you setting isLoading: true on success? I would suggest to create 3 actions instead of 2:
SAVE_USER_START (which you dispatch before sending a request),
set isLoading to true,
SAVE_USER_SUCCESS - set isLoading to false
SAVE_USER_FAILURE - set isLoading to false
I would suggest to look into redux-form library. It provides configuration option to clear fields after submit out of the box.