How do I update a component and go back to its initial state?

Asked

Viewed 1,001 times

3

Authentication:

  1. It has a login screen produced with native language (React-Native), which when logging into a remote server through a webservice, accessed by an imported component within my app, where it returns me a jwt hash, and some user information, when logged in correctly.

  2. Then it makes a second authentication, which is in our database, where it takes this user’s complete data, and creates a navigation and cookie access authentication, which is loaded into a webview.

  3. This webview is set within the native app, and is rendered by checking if there is a jwt.

  4. Through browsing the webview, I have control of urls that are sent to the native layer (React-Native), one of these urls and the output route (logout), so when I tap this page the system logout, but the application gets a blank screen and loses the native login home screen, and this is the problem:

    The native screen (React-Native) does not update, and I cannot restart the login process after that.

I am using Hooks on the page, IE, there is no longer an instantiated class where I can stay reinstalling the render with the componentDidMount().

To documentation has nothing on how to work with Hooks and webview.

There’s this github that doesn’t explain anything either how to use with Hooks.

I even tried to do as if it was an App Re-turn, but it didn’t work, see the code:

import React, { useState, Fragment, Component } from 'react'
import { SafeAreaView } from 'react-native'
import { WebView, onNavigationStateChange } from 'react-native-webview'
// import { createAppContainer } from 'react-navigation';  
// import { createStackNavigator } from 'react-navigation-stack';
import { Login } from 'combo-mobile'
import { NativeModules, Platform, Alert, Button, TextInput, View, StyleSheet, Text, Modal, Keyboard, Linking } from 'react-native'
import CookieManager from 'react-native-cookies'
import { 
  DOMAIN_APP,
  TEST_PARAMS_LOGIN,
  APPLICATION_ENV
} from './src/config/env'
import {version as appVersion} from './app.json'

//O aplicativo que é exportado...

const App = () => {
  
  const [jwt, setJWT] = useState(null)
  const [urlWebview, setURL] = useState(`${DOMAIN_APP}/path/index`)
  
  const json_encode_platform = btoa(JSON.stringify({
    tk_os:Platform.OS, 
    tk_os_version:Platform.Version,
    tk_version_app:appVersion
  }));

  const jsLib = `window.postMessage("{script:'${DOMAIN_APP}/js/add-script-${Platform.OS}-platform.js',platform:'${json_encode_platform}'}");`

  const _onNavigationStateChange = (webViewState) => {
    console.log('nav -> '+Date.now())
    console.log(webViewState)
        if (typeof webViewState.url !== 'undefined') {
          _loadingStatus = false
          setURL(webViewState.url)
  
          if(urlWebview !==  `${DOMAIN_APP}/path/index`) {
             console.log('navigation-change')
            if(urlWebview.indexOf('external_id') !== -1) {
                Linking.openURL(urlWebview);
            }

            if (urlWebview.indexOf('/logout') !== -1) {
                console.log('fez logout...')
                CookieManager.clearAll();
                console.log('limpei login')
                 /* 
                  AQUI DEVERIA VOLTAR TUDO NOVAMENTE PARA O ORIGINAL
                  ::: SÓ QUE ESTÁ DEIXANDO A TELA EM BRANCO ::: 
                */
                 setJWT(false)
                 setURL(`${DOMAIN_APP}/path/index`)

                /*
                   AQUI É A TENTATIVA DE FAZER ELE 
                   RENDERIZAR, SÓ QUE NÃO FUNCIONOU
                */
                 return goWebcombo()
               
            }
          }
       }
   }


  const _createCookie = (name, value, call) => {
      CookieManager.setFromResponse(`${DOMAIN_APP}/, ${name}=${value};path=/;expires=2030-05-30T12:30:00.00-05:00;secure`)
          .then((res) => {
            console.log('setFromResponse.set =>', res);
            CookieManager.get(`'${DOMAIN_APP}/'`)
            .then((resGet) => {
                console.log(resGet[name]);
                if (resGet[name] != undefined ){
                    console.log('COOKIE SETADO????? =>', resGet);
                    call();
                }
              });
          });
  }
  
  const _cookiesTypeLogin = () => {
      if (DOMAIN_APP) {
          CookieManager.clearAll() 
          _createCookie('tk_os', Platform.OS, (res) => {
               _createCookie('type_login','app', (res) => {
              })
          })
      }
  }

  let _loadingStatus = true;

 const defaultUrlAuthenticate = `${DOMAIN_APP}/path/api/oauth/auth?tk_os=${Platform.OS}&tk_os_version=${Platform.Version}&tk_version_app=${appVersion}&jwt_combo=${jwt}&url=${encodeURIComponent(
  //   `${DOMAIN_APP}/path/index`
  // )}`

 
 //O comboJWT é o componente externo que atribui o jwt

 //render() {
  const webCombo = (
    <Fragment>
      <Login product="productName" onLoginCombo={({ comboJWT }) => {
         setJWT(comboJWT)  
          if(jwt) {
            //seta cookie da origem
             _cookiesTypeLogin()
          }
      }} />
      {
       //aqui verifica se o jwt foi criado e carrega a webview
        jwt && (
          <SafeAreaView style={{ flex: 1 }}>
            <WebView
              style={{ flex: 1 }}
              onNavigationStateChange={_onNavigationStateChange}
              onError={_onNavigationStateChange}
              source={{ uri: defaultUrlAuthenticate }}
              javaScriptEnabledAndroid={true}
              mixedContentMode={'compatibility'}
              allowsInlineMediaPlayback={true}
              javaScriptEnabled={true}
              domStorageEnabled={true}
              injectedJavaScript={jsLib}
              startInLoadingState={_loadingStatus}
              thirdPartyCookiesEnabled={true}
              useWebKit={true}
              sharedCookiesEnabled={true}
              onMessage={e => {
                 //print the data coming from the angular app to the console, data.newUrl should have the new url
                console.log("data from angular app:",e)
                console.log("teste", e.nativeEvent)
                e.nativeEvent.loading = false;
                _loadingStatus = false;
                 const dataMessage = e.nativeEvent.data;
                     if (dataMessage.open_url != undefined) { 
                         Linking.openURL(dataMessage.open_url);
                     }
                }
              }
              />
          </SafeAreaView>
        )
      }
    </Fragment>
  )
  const goWebcombo = () => {
     return webCombo;
  }
  //criei como um método só para tentar renderizar (só que não fez nada)
  return goWebcombo();
  //  }
}

export default App

I tried using useEffect, but see the error that gave:

inserir a descrição da imagem aqui

  • The problem is that you can’t use a hook equivalent to componentDidMount()?

  • I think it’s: useEffect or useCallback, but I don’t know how to apply their use here.

  • I wondered if it wouldn’t be useEffect(App, [])...

  • Basically, the equivalent of componentDidMount is the useEffect(função, []), if you want his "substitute".

  • How would you use the componentDidMount? Would it work? Have you ever tried to convert this functional component to a class-based?

  • I mean, basically a modal that was closed on top..., only they changed everything... and I’m having to redo it, using hook.

  • If you execute what’s inside componentDidMount solve your problem? If yes, just run what’s inside the body with use Effect the way I said it there...

Show 3 more comments

1 answer

0


The problem has been solved by placing / removing from Asyncstorage, and including useEffect:

import React, { useState, useEffect, Fragment, Component } from 'react'
import AsyncStorage from '@react-native-community/async-storage'

  const [loadingToken, setLoadingToken] = useState(true)

  const SafeArea = ( <SafeAreaView style={{ flex: 1 }}>
    <WebView
      style={{ flex: 1 }}
      onNavigationStateChange={_onNavigationStateChange}
      onError={_onNavigationStateChange}
      source={{ uri: gutenURL }}
      javaScriptEnabledAndroid={true}
      mixedContentMode={'compatibility'}
      allowsInlineMediaPlayback={true}
  ...
 )

   useEffect(() => {
      AsyncStorage.getItem('comboJWT').then((data) => {
        if (data && !jwt) {
          setJWT(data)
        }
        setLoadingToken(false)
      })
    })

    const _onNavigationStateChange = (webViewState) => {
        if (typeof webViewState.url !== 'undefined') {
            _loadingStatus = false
            setURL(webViewState.url)

            if (urlWebview !== `${DOMAIN_APP}/path/index`) {

                if (IsValid(urlWebview,'/logout')) {
                    AsyncStorage.removeItem('comboJWT')
                    setJWT(false)
                    setStatus(0)
                }
            }
        }
    }

const webCombo = (
      <Fragment>
        {
          !jwt && !loadingToken && comboJWT && (
            <Login product="productName" onLoginCombo={({ comboJWT }) => {
                setJWT(comboJWT)  
                  AsyncStorage.setItem('comboJWT', comboJWT)
                if(jwt) {
                    setStatus(statusLogin + 1)
                }
            }} />
          )
        }
        {
          jwt && safeArea
        }
      </Fragment>
    )
    const goWebcombo = () => {
        return webCombo;
    }
    return goWebcombo(); 

Browser other questions tagged

You are not signed in. Login or sign up in order to post.