Application resets to initial screen after form submitting and changing state

Yur D

Application resets to initial screen after form submitting (redux-form or Formik). The Login screen is the second screen in initial route (first is the Start screen). After submitting to occur a call dispatch and return new state -> { ...state, ...{ isLoading: true } } and on this step my app was resets.

What am I doing wrong? How to make the form work without a reset?

LoginScreen.js

import React, { Component } from 'react'
import { View, Text, Button } from 'react-native'
import { connect } from 'react-redux'

import { LoginForm } from '../../forms'
import { userLogin } from '../../store/modules/account'

import s from './styles'

class LoginScreen extends Component {

  onLogin = (values, bag) => {
    const { userLogin } = this.props
    const { email, password } = values
    userLogin({ email, password })
  }

  render() {
    const { account, navigation } = this.props

    return (
      <View style={s.wrapper}>
        <View style={s.mainContainer}>
          <Text>This is SignIiiiiiin!</Text>
          <LoginForm
            handleLogin={this.onLogin}
          />
        </View>
      </View>
    )
  }
}

const mapStateToProps = ({ account }) => ({
  account,
})

export default connect(mapStateToProps, {
  userLogin
})(LoginScreen)

LoginForm.js

import React, { Component } from 'react'
import { View, TouchableOpacity, Button } from 'react-native'
import { Formik } from 'formik'

import { FieldInput } from '../../components'

import s from './styles'

class LoginForm extends Component {

  render() {
    const {
      handleLogin,
    } = this.props

    return (
      <View style={s.wrapper}>
        <Formik
          initialValues={{ email: '', password: '', confirmPassword: '' }}
          onSubmit={handleLogin}
          render={({
             values,
             handleSubmit,
             setFieldValue,
             errors,
             touched,
             setFieldTouched,
             isValid,
             isSubmitting,
           }) => (
            <React.Fragment>
              <FieldInput
                label="Email"
                autoCapitalize="none"
                value={values.email}
                onChange={setFieldValue}
                onTouch={setFieldTouched}
                name="email"
                error={touched.email && errors.email}
              />
              <FieldInput
                label="Password"
                autoCapitalize="none"
                secureTextEntry
                value={values.password}
                onChange={setFieldValue}
                onTouch={setFieldTouched}
                name="password"
                error={touched.password && errors.password}
              />
              <FieldInput
                label="Confirm Password"
                autoCapitalize="none"
                secureTextEntry
                value={values.confirmPassword}
                onChange={setFieldValue}
                onTouch={setFieldTouched}
                name="confirmPassword"
                error={touched.confirmPassword && errors.confirmPassword}
              />
              <Button
                backgroundColor="blue"
                title="Submit"
                onPress={handleSubmit}
                disabled={!isValid || isSubmitting}
                loading={isSubmitting}
              />
            </React.Fragment>
          )}
        />
      </View>
    )
  }
}

export default LoginForm

store/index.js

import { applyMiddleware, compose, createStore } from 'redux'
import thunk from 'redux-thunk'
import { persistStore, persistReducer } from 'redux-persist'
import logger from 'redux-logger'
import storage from 'redux-persist/lib/storage'

import makeRootReducer from './reducers'

const persistConfig = {
  key: 'root',
  storage,
  blacklist: ['account']
}

const persistedReducer = persistReducer(persistConfig, makeRootReducer)

const enhancer = compose(applyMiddleware(thunk, logger))

export default function configureStore() {
  const store = createStore(persistedReducer, enhancer)
  const persistor = persistStore(store)

  return { store, persistor }
}

store/modules/account.js

import { AsyncStorage } from 'react-native'
import { cloneDeep, assignIn, merge } from 'lodash'
import axios from 'axios'
import moment from 'moment'

import CNST from '../constants'
import { ENV } from '../../config'

// ------------------------------------
// Actions
// ------------------------------------

export function userLogin(data = {}) {
  const username = data.email
  const password = data.password

  return (dispatch) => {
    dispatch({
      type: CNST.ACCOUNT.LOGIN.LOADING
    })
    /*
    axios.post(`${ENV.ROOT_URL}/user/login`, { username, password })
      .then((response) => {
        const { token } = response.data
        const validFrom = moment().format()
        dispatch({
          type: CNST.ACCOUNT.LOGIN.SUCCESS,
          response: { token, username, validFrom }
        })
        return response
      })
      .catch((error) => {
        console.log('error', error.response)
        dispatch({
          type: CNST.ACCOUNT.LOGIN.FAILED,
          response: error
        })
      })
    */
  }
}


// ------------------------------------
// Reducers
// ------------------------------------

const initialState = {
  id: '',
  email: '',
  username: '',
  token: '',
  error: {},
  isLoading: false
}

export default function accountReducer(state = cloneDeep(initialState), action) {
  switch (action.type) {
    case CNST.ACCOUNT.LOGIN.SUCCESS: {
      // console.log('action', action)
      const { token, username, validFrom } = action.response
      const _items = [
        ['token', token || ''],
        ['username', username || ''],
        ['validFrom', validFrom || ''],
      ]
      AsyncStorage.multiSet(_items)

      return { ...state, ...{ error: {}, token, username, email: username, isLoading: false } }
    }
    case CNST.ACCOUNT.LOGIN.FAILED:
      return { ...state, ...{ error: action.response, isLoading: false } }
    case CNST.ACCOUNT.LOGIN.LOADING:
      return { ...state, ...{ isLoading: true } }
    default:
      return state
  }
}

store/constants/account.js

export default {
  LOGIN: {
    LOADING: 'LOGIN',
    SUCCESS: 'LOGIN_SUCCESS',
    FAILED: 'LOGIN_FAILED'
  }
}

store/reducers.js

import { combineReducers } from 'redux'

import account from './modules/account'

export default combineReducers({
  account,
})
Yur D

I fixed this issue. The problem was in the main container where I mounting Navigator and pass state for changing routes between different Stacks. I passed all state object and when one of object`s item was changed Navigator resetting navigation states.

. . .
    return (
      <View style={{ flex: 1 }}>
        <Navigator
          onNavigationStateChange={() => Keyboard.dismiss()}
        />
      </View>
    )
  }
}

const mapStateToProps = ({ account }) => ({
  account // <-- bad idea
  token: account.token // <-- good one
})

export default connect(mapStateToProps, {
  getSomeData
})(MainContainer)

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

CABasicAnimation resets to initial value after animation completes

Ngrx Store Resets after browser refresh. How to make the application preserve the state?

submitting simple form and capturing before and after screen

React state resets back to initial value after component is mounted

React setState doesn't update the state after submitting input form

Form clears after submitting

AJAX not submitting the form after validation

Submitting a form using jQuery and Ajax changing the action

UIView is resets to initial value after presenting other view controller

Multiple form elements in different divs-- submitting one resets the others

Form not submitting after form validation

Variable isn't changing after form submitting

qdisc resets after changing to htb

Empty modelAttribute after submitting a form

react update screen after changing values in the state

Submitting form after validating inputs

screen not re-rendering after changing state

changing my JSON data when submitting form

Form not submitting after bootstrap confirmation

Loading a component after submitting a form

Jquery form not submitting after validation

Vuetify reset form after submitting

Changing the initial screen

Unable to clear the form after submitting

How to redirect after submitting form

React Native switch component's state resets after re-entering screen

Why am I getting the following warning after submitting a form using Formik: A component is changing a controlled input to be uncontrolled

React/Next Updates State and Resets it After useEffect

Submitting valid form and changing style

TOP Ranking

  1. 1

    Failed to listen on localhost:8000 (reason: Cannot assign requested address)

  2. 2

    Loopback Error: connect ECONNREFUSED 127.0.0.1:3306 (MAMP)

  3. 3

    How to import an asset in swift using Bundle.main.path() in a react-native native module

  4. 4

    pump.io port in URL

  5. 5

    Compiler error CS0246 (type or namespace not found) on using Ninject in ASP.NET vNext

  6. 6

    BigQuery - concatenate ignoring NULL

  7. 7

    ngClass error (Can't bind ngClass since it isn't a known property of div) in Angular 11.0.3

  8. 8

    ggplotly no applicable method for 'plotly_build' applied to an object of class "NULL" if statements

  9. 9

    Spring Boot JPA PostgreSQL Web App - Internal Authentication Error

  10. 10

    How to remove the extra space from right in a webview?

  11. 11

    java.lang.NullPointerException: Cannot read the array length because "<local3>" is null

  12. 12

    Jquery different data trapped from direct mousedown event and simulation via $(this).trigger('mousedown');

  13. 13

    flutter: dropdown item programmatically unselect problem

  14. 14

    How to use merge windows unallocated space into Ubuntu using GParted?

  15. 15

    Change dd-mm-yyyy date format of dataframe date column to yyyy-mm-dd

  16. 16

    Nuget add packages gives access denied errors

  17. 17

    Svchost high CPU from Microsoft.BingWeather app errors

  18. 18

    Can't pre-populate phone number and message body in SMS link on iPhones when SMS app is not running in the background

  19. 19

    12.04.3--- Dconf Editor won't show com>canonical>unity option

  20. 20

    Any way to remove trailing whitespace *FOR EDITED* lines in Eclipse [for Java]?

  21. 21

    maven-jaxb2-plugin cannot generate classes due to two declarations cause a collision in ObjectFactory class

HotTag

Archive