initialValues does not get update when updating the form - javascript

I have a form called Client which has a single form which handles both add and edit. Add is working but when editing the form(form
is populated with initialValues if it's and edit form), the initialValues does not get update. I mean, if I go to client A form and update the
field called client_name from 'abc' to 'xyz' then the client_name will be saved as 'xyz' in server but the initialValues does not get update
so if i again go to same form without refreshing the page and save the form without changing anything then client_name is saved with previous
value i. 'abc' because initialValues is not updated when updating the field.
Here is my code
import React, { Component } from 'react';
import { reduxForm, initialize } from 'redux-form';
const mapDispatchToProps = (dispatch, props) => ({
addClient: clientData => dispatch(addClient(clientData)),
editClient: clientData => dispatch(editClient(clientData)),
loadClient: () => dispatch(loadClient(props.match.params.company)),
resetClient: () => dispatch(resetClient()),
});
const mapStateToProps = createStructuredSelector({
initialValues: selectClient(),
});
class Client extends Component<propsCheck> {
state = {
client: initialState,
isLoading: false,
};
componentDidMount() {
if (this.props.match.params.company) {
this.props.loadClient();
}
}
componentWillReceiveProps(nextProps) {
if (this.props.match.params.company) {
this.props.loadClient();
} else {
this.props.resetClient();
}
}
handleChange = ({ target: { name, value } }) => {
this.setState({ client: { ...this.state.client, [name]: value } });
};
handleSubmit = event => {
event.preventDefault();
const { client } = this.state;
const { initialValues, addClient: add, editClient: edit } = this.props;
if (isEmpty(initialValues)) {
add(client);
} else {
const updatedClient = updatedValue(initialValues, client, 'id');
edit(updatedClient);
}
this.setState({ isLoading: true });
};
render() {
const { invalid, submitting, initialValues } = this.props;
return (
<ClientForm
loading={this.state.isLoading}
handleChange={this.handleChange}
handleSubmit={this.handleSubmit}
disabled={invalid || submitting}
type={initialValues && initialValues.id ? 'Edit' : 'Add'}
reset={this.props.reset}
history={this.props.history}
/>
);
}
}
const withReduxForm = reduxForm({
form: 'clientForm',
fields: requiredFields,
validate,
enableReinitialize: true,
})(Client);
export default connect(
mapStateToProps,
mapDispatchToProps,
)(withReduxForm);

Your initial values are being populated from redux state (selectClient in mapStateToProps) right? So, when you update/edit the client_name, are you changing the data in redux??

Related

TypeError: updateElement is not a function

I am trying to update an element from an array by adding an object as a property like shown in this picture
When a user clicks on a single node button, a modal appears the user fills the form and then it is addes as a property for this node.
But for some reason I get this type error that says that the updateElement is not a function.
BTW, I am using Redux & react-flow-renderer libraries.
Reducer
import * as types from '../actions/types';
const initialState = {
elements: []
};
const flow = (state = initialState, action) => {
switch (action.type) {
case types.UPDATE_ELEMENT:
return {
...state,
elements: state.elements.map((e) => {
if (e.id === action.payload.id) {
e = {
...e,
options: action.payload.options,
};
}
return e;
}),
};
default:
return state;
}
};
export default flow;
Action
import { UPDATE_ELEMENT } from './types';
export const updateElement = (data) => (dispatch) => {
dispatch({
type: UPDATE_ELEMENT,
payload: data,
});
};
Node modal
import React, { useState } from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import { updateElement } from '../../../../redux/actions/flow';
const VPCNodeModal = (props, { updateElement }) => {
const [formData, setFormData] = useState({
instance: '',
});
// options
const { instance } = formData;
const onFormChange = (e) =>
setFormData({ ...formData, [e.target.name]: e.target.value });
const onSubmitForm = () => {
const update = {
id: selectedElement.id,
options: formData,
};
updateElement(update);
};
return (
<>
<Modal {...props}>
<form
onSubmit={(e) => {
e.preventDefault();
onSubmitForm();
}}
>
<label>
<span> Instance name:</span>
<input
type='text'
name='instance'
value={instance}
onChange={onFormChange}
/>
</label>
<button type='submit'>Submit</button>
</form>
</Modal>
</>
);
};
VPCNodeModal.propTypes = {
updateElement: PropTypes.func.isRequired
};
export default connect(null, { updateElement })(VPCNodeModal);
Issue is while receiving the props.
change
const VPCNodeModal = (props, { updateElement }) => {
to
const VPCNodeModal = (props) => {
const { updateElement } = props;
updateElement is a props was passes in VPCNodeModal. So you should update like this with spread operator
const VPCNodeModal = ({ updateElement, ...props }) => {

Redux + Hooks useDispatch() in useEffect calling action twice

I'm beginner in redux & hooks. I am working on form handling and trying to call an action through useDispatch hooks but it is calling my action twice.
I'm referring this article.
Here is the example:
useProfileForm.js
import { useState, useEffect } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { fetchProfile } from '../../../redux/profile/profile.actions';
const useProfileForm = (callback) => {
const profileData = useSelector(state =>
state.profile.items
);
let data;
if (profileData.profile) {
data = profileData.profile;
}
const [values, setValues] = useState(data);
const dispatch = useDispatch();
useEffect(() => {
dispatch(fetchProfile());
}, [dispatch]);
const handleSubmit = (event) => {
if (event) {
event.preventDefault();
}
callback();
};
const handleChange = (event) => {
event.persist();
setValues(values => ({ ...values, [event.target.name]: event.target.value }));
};
return {
handleChange,
handleSubmit,
values,
}
};
export default useProfileForm;
Action
export const FETCH_PROFILE_BEGIN = "FETCH_PROFILE_BEGIN";
export const FETCH_PROFILE_SUCCESS = "FETCH_PROFILE_SUCCESS";
export const FETCH_PROFILE_FAILURE = "FETCH_PROFILE_FAILURE";
export const ADD_PROFILE_DETAILS = "ADD_PROFILE_DETAILS";
function handleErrors(response) {
if (!response.ok) {
throw Error(response.statusText);
}
return response;
}
function getProfile() {
return fetch("url")
.then(handleErrors)
.then(res => res.json());
}
export function fetchProfile() {
return dispatch => {
dispatch(fetchProfileBegin());
return getProfile().then(json => {
dispatch(fetchProfileSuccess(json));
return json;
}).catch(error =>
dispatch(fetchProfileFailure(error))
);
};
}
export const fetchProfileBegin = () => ({
type: FETCH_PROFILE_BEGIN
});
export const fetchProfileSuccess = profile => {
return {
type: FETCH_PROFILE_SUCCESS,
payload: { profile }
}
};
export const fetchProfileFailure = error => ({
type: FETCH_PROFILE_FAILURE,
payload: { error }
});
export const addProfileDetails = details => {
return {
type: ADD_PROFILE_DETAILS,
payload: details
}
};
Reducer:
import { ADD_PROFILE_DETAILS, FETCH_PROFILE_BEGIN, FETCH_PROFILE_FAILURE, FETCH_PROFILE_SUCCESS } from './profile.actions';
const INITIAL_STATE = {
items: [],
loading: false,
error: null
};
const profileReducer = (state = INITIAL_STATE, action) => {
switch (action.type) {
case ADD_PROFILE_DETAILS:
return {
...state,
addProfileDetails: action.payload
}
case FETCH_PROFILE_BEGIN:
return {
...state,
loading: true,
error: null
};
case FETCH_PROFILE_SUCCESS:
return {
...state,
loading: false,
items: action.payload.profile
};
case FETCH_PROFILE_FAILURE:
return {
...state,
loading: false,
error: action.payload.error,
items: []
};
default:
return state;
}
}
export default profileReducer;
**Component:**
import React from 'react';
import { connect } from 'react-redux';
import useProfileForm from './useProfileForm';
import { addProfileDetails } from '../../../redux/profile/profile.actions';
const EducationalDetails = () => {
const { values, handleChange, handleSubmit } = useProfileForm(submitForm);
console.log("values", values);
function submitForm() {
addProfileDetails(values);
}
if (values) {
if (values.error) {
return <div>Error! {values.error.message}</div>;
}
if (values.loading) {
return <div>Loading...</div>;
}
}
return (
<Card>
...some big html
</Card>
)
}
const mapDispatchToProps = dispatch => ({
addProfileDetails: details => dispatch(details)
});
export default connect(null, mapDispatchToProps)(EducationalDetails);
Also when I'm passing data from const [values, setValues] = useState(data); useState to values then ideally I should receive that in component but I'm not getting as it is showing undefined.
const { values, handleChange, handleSubmit } = useProfileForm(submitForm);
values is undefined
The twice dispatch of action is probably because you have used React.StrictMode in your react hierarchy.
According to the react docs, in order to detect unexpected sideEffects, react invokes a certain functions twice such as
Functions passed to useState, useMemo, or useReducer
Now since react-redux is implemented on top of react APIs, actions are infact invoked twice
Also when I'm passing data from const [values, setValues] = useState(data); useState to values then ideally I should receive that in component but I'm not getting as it is showing undefined.
To answer this question, you must know that values is not the result coming from the response of dispatch action from reducer but a state that is updated when handleChange is called so that is supposed to remain unaffected by the action
I think you mean to expose the redux data from useProfileForm which forgot to do
const useProfileForm = (callback) => {
const profileData = useSelector(state =>
state.profile.items
);
let data;
if (profileData.profile) {
data = profileData.profile;
}
const [values, setValues] = useState(data);
const dispatch = useDispatch();
useEffect(() => {
dispatch(fetchProfile());
}, [dispatch]);
const handleSubmit = (event) => {
if (event) {
event.preventDefault();
}
callback();
};
const handleChange = (event) => {
event.persist();
setValues(values => ({ ...values, [event.target.name]: event.target.value }));
};
return {
handleChange,
handleSubmit,
values,
data // This is the data coming from redux store on FetchProfile and needs to logged
}
};
export default useProfileForm;
You can use the data in your component like
const { values, handleChange, handleSubmit, data } = useProfileForm(submitForm);

how to save react js state into localstorage

I have no idea How to store the react js state into localstorage.
import React, { Component } from 'react'
import './App.css';
import { auth,createUserProfileDocument } from './firebase/firebase.utils'
import { TodoForm } from './components/TodoForm/TodoForm.component'
import {TodoList} from './components/TodoList/TodoList.component'
import {Footer} from './components/footer/footer.component'
import Header from '../src/components/header/header.component'
import {Redirect} from 'react-router-dom'
import {connect} from 'react-redux'
import {setCurrentUser} from './redux/user/user.actions'
export class App extends Component {
constructor(props) {
super(props)
this.input=React.createRef()
this.state = {
todos:[
{id:0, content:'Welcome Sir!',isCompleted:null},
]
}
}
todoDelete = (id) =>{
const todos = this.state.todos.filter(todo => {
return todo.id !== id
})
this.setState({
todos
})
}
toDoComplete = (id,isCompleted) =>{
console.log(isCompleted)
var todos = [...this.state.todos];
var index = todos.findIndex(obj => obj.id === id);
todos[index].isCompleted = !isCompleted;
this.setState({todos});
console.log(isCompleted)
}
addTODO = (todo) =>{
todo.id = Math.random()
todo.isCompleted = true
let todos = [...this.state.todos, todo]
this.setState({
todos
})
}
unsubscribeFromAuth = null;
componentDidMount() {
const { setCurrentUser } = this.props;
this.unsubscribeFromAuth = auth.onAuthStateChanged(async userAuth => {
if (userAuth) {
const userRef = await createUserProfileDocument(userAuth);
userRef.onSnapshot(snapShot => {
setCurrentUser({
id: snapShot.id,
...snapShot.data()
});
});
}
setCurrentUser(userAuth);
});
}
componentWillUnmount() {
this.unsubscribeFromAuth();
}
render() {
return (
<div className='App'>
<Header />
<TodoForm addTODO={this.addTODO} />
<TodoList
todos={this.state.todos}
todoDelete={ this.todoDelete}
toDoComplete={ this.toDoComplete}
/>
<Footer/>
</div>
)
}
}
const mapStateToProps = ({ user }) => ({
currentUser: user.currentUser
});
const mapDispatchToProps = dispatch => ({
setCurrentUser: user => dispatch(setCurrentUser(user))
});
export default connect(
mapStateToProps,
mapDispatchToProps
)(App);
in my input Form
import './TodoForm.style.css'
export class TodoForm extends Component {
constructor(props) {
super(props)
this.state = {
content : ''
}
}
handleChange = (e) =>{
this.setState({
content: e.target.value
})
}
handleSubmit =(e) =>{
e.preventDefault();
this.props.addTODO(this.state);
this.setState({
content: ''
})
}
render() {
return (
<div className='inputTask'>
<form onSubmit={ this.handleSubmit}>
<input
className="textBox"
type='text'
onChange={ this.handleChange}
value={this.state.content}
placeholder='what you want to do ...'
/>
</form>
</div>
)
}
}
export default TodoForm
I have no idea How to store the react js state into localstorage.
i searched on internet but unable to find the exact solution all the codes that i think is necessary post.
You can use reactLocalStorage to save any data in local storage
import {reactLocalStorage} from 'reactjs-localstorage';
reactLocalStorage.set('var', true);
reactLocalStorage.get('var', true);
reactLocalStorage.setObject('var', {'test': 'test'});
reactLocalStorage.getObject('var');
reactLocalStorage.remove('var');
reactLocalStorage.clear();
Read out the localStorage item in the componentDidMount callback. Simply read the item you want to get, check if it exists and parse it to a usable object, array or datatype that need. Then set the state with the results gotten from the storage.
And to store it, simply handle it in an event handler or helper method to update both the state and the localStorage item.
class ExampleComponent extends Component {
constructor() {
super();
this.state = {
something: {
foo: 'bar'
}
}
}
componentDidMount() {
const storedState = localStorage.getItem('state');
if (storedState !== null) {
const parsedState = JSON.parse(storedState);
this.setState({ something: parsedState });
}
}
clickHandler = (event) => {
const value = event.target.value;
const stringifiedValue = JSON.stringify(value);
localStorage.setItem('state', stringifiedValue);
this.setState({ something: value });
}
render() {
return (
<button onClick={clickHandler} value={this.state.something}>Click me</button>
);
}
}
Set data in localStorage
key-value pair :
localStorage.setItem('key_name',"value");
object
localStorage.setItem('key_name', JSON.stringify(object));
Remove data from localStorage
localStorage.removeItem('key_name');
Get data from localStorage
let data = localStorage.getItem('key_name');
object :
let data = JSON.parse(localStorage.getItem('key_name'));
clear localStorage (delete all data)
localStorage.clear();

reducer does not update state in react redux

I am trying update state using react-redux but the state is not being updated.
new value is coming to
"if (action.type === 'SET_LOGGED_IN')"
in reducer, but not updating the isLoggedIn as true.
What was wrong?
find the code
Login.js
function handleLoginClick(username, password, e) {
e.preventDefault();
post('/createUser', { username, password })
.then(({ status }) => {
if (status === 200) {
console.log(this.props);
this.props.setLoggedIn(true);
this.props.history.push('/');
}else{
this.props.setLoggedIn(false);
}
})
.catch(error => {
.........
})
}
..................
const mapStateToProps = state => {
return {isLoggedIn : state.reducer.isLoggedIn};};
const mapDispatchToProps = dispatch => {
return {setLoggedIn : (value) => dispatch({type: 'SET_LOGGED_IN', value: value}),}};
export default compose(
withStyles(styles),
withRouter,
connect(mapStateToProps, mapDispatchToProps)
)(NewLogin);
reducer.js
import { combineReducers } from 'redux';
import { reducer as reduxFormReducer } from 'redux-form';
const initialStates = {
isLoggedIn : false
};
const reducers = combineReducers({
reducer : (state = initialStates, action) => {
//console.log(action);
if (action.type === 'SET_LOGGED_IN') {
//console.log(action);
return {
...state,
isLoggedIn: action.value
};
}
return state;
},
form: reduxFormReducer, // mounted under "form"
});
export default reducers;
-Fixed the error-
In my code, state is updated correctly. When I accessing, I had used state.isLoggedIn which is undefined. I replaced it from state.reducer.isLoggedIn.
Now everything works charm.
Thank you #UmairFarooq , #VladimirBogomolov and all who commented and gave a try to fix it.
const mapStateToProps = state => {
return {
isLoggedIn : state.reducer.isLoggedIn
};
};
Think there might be a problem with your mapStateToProps. Try accessing your isLoggedIn state like :
const mapStateToProps = state => {
return {isLoggedIn : state.isLoggedIn};};
use componentwillupdate() to controllr when to update
return false to not update
You should be calling dispatch differently:
const mapDispatchToProps = (dispatch, val) => {
return {
setLoggedIn : (val) => dispatch({ type: 'SET_LOGGED_IN', value: val }),
}
};
Try that and it should work for you.

Why mapStateToProps return empty object when state has been mutated?

I create action
export const KIDS_LOAD = 'KIDS_LOAD';
export const kidsLoad = (data) => ({
type: KIDS_LOAD,
payload: data ,
});
I create reducer
import { KIDS_LOAD } from '../customActions/KidsActions';
export default (state = {}, { type, payload }) => {
if (type === KIDS_LOAD) {
return { ...state,
img: payload.img,
kidsInfo: payload.kidsInfo
};
}
return state;
}
I dispatch action
componentWillMount() {
this.props.setSidebarVisibility(true);
const { kidsLoad, record } = this.props;
kidsLoad({
img : 'https://s18670.pcdn.co/wp-content/uploads/care_about_grades_middle_school.jpg',
kidsInfo: {
kidName : 'Sasha',
kidAge : '19',
kidHandType : 'Right',
kidGender : 'Boy',
}
})
console.log( this.props.kidsTabData)
}
I map state
const mapStateToProps = state => ({
kidsTabData: state.kidsReducer,
isLoading: state.admin.loading > 0,
});
export default connect(mapStateToProps, { setSidebarVisibility, kidsLoad })(withStyles(styles)(MyLayout));
Store mutated
But console.log( this.props.kidsTabData) return empty object {}.
Can you tell where I’m wrong? It seems to me that everything goes to the store correctly, but the initialState gets to props.
The redux action kidsLoad is asynchronous.
Try the console.log in componentDidUpdate
componentDidUpdate(){
console.log(this.props.kidsTabData)
}

Categories

Resources