Esta es una biblioteca nativa React creada para manejar sincronizaciones con backend. Imagine que se envía alguna acción y en ese momento no tenía Internet, con esta biblioteca podrá detectar esa ocurrencia, guardar la información relacionada con la acción y enviarla nuevamente cuando se restablezca la conexión. La mejor parte de esto, es que esta biblioteca es muy fácil de usar.
redux
react-redux
@react-native-community/netinfo > Tendrá que instalar esta biblioteca antes, aquí están los pasos: Información neta
@react-native-community/async-storage
yarn add sync-offline-actions
o NPM:
npm install --save sync-offline-actions
Proporcionamos cuatro herramientas para que pueda manejar el comportamiento de su proyecto. Esos son:
Este es un componente que tendrá que usar en la raíz de su proyecto. Es totalmente necesario que use este componente en la raíz de su proyecto porque tiene que existir en un componente que siempre está vivo. Este componente tendrá que envolver los otros componentes que tiene en la raíz de su proyecto, por ejemplo:
import { RestoreOfflineActions } from 'sync-offline-actions' ;
import actions from '@redux/some/actions' ;
// Some stuff
// Render/return
< RestoreOfflineActions
sections = { [
{ generalCondition : /* Condition of something */ , actions : { name : 'login' , associatedAction : actions . login } }
] } >
< AppNavigator />
</ RestoreOfflineActions > Las sections de Prop es totalmente obligatoria usar esto. Veamos la estructura:
Pasará una variedad de secciones de su aplicación. Cada sección podría tener múltiples acciones que desea enviar si ha sucedido. Por ejemplo, imagine que quiero establecer algunas acciones para la sección de Authorization de mi aplicación y algunas acciones para la sección de App . Estableceré la condición para cada sección en el valor generalCondition . Tendré una matriz como esta:
sections={[
{ generalCondition: /* Condition to know if the user is not logged in */, actions: [{ name: 'someAction', associatedAction: actions.someAction }] },
{ generalCondition: /* Condition to know if the user is logged in */, actions: [{ name: 'otherAction', associatedAction: actions.otherAction }, {name: 'otherAction2', associatedAction: actions.otherAction2 }] }
]}
Cada sección tiene acciones asociadas. Cada acción tendrá un name (veremos la importancia de este nombre más adelante) y una associatedAction , esta última será la acción que desea enviar cuando se restablezca la conexión.
Esta es una función para guardar los momentos, acciones u ocurrencys que se enviarán más adelante. Aquí hay algunos ejemplos de uso:
// actions.js
import { saveActionToBeSync } from 'sync-offline-actions' ;
// Some code
// Imagine that you have an action and that action which send a request to back, that action will fail and you will want to save that request to do it later. You will do
saveActionToBeSync ( 'someAction' , [ arg1 , arg2 , arg3 ] ) ;
//Thunk Action example
function myThunkActionCreator ( id , someValue ) {
return async ( dispatch , getState ) => {
dispatch ( { type : "REQUEST_STARTED" } ;
let response ;
try {
response = myAjaxLib . post ( "/someEndpoint" , { id , data : someValue } ) ;
} catch ( error ) {
saveActionToBeSync ( 'someThunkAction' , [ id , someValue ] ) ; // here we register the failed event that want to dispatch when the connection is restored
dispatch ( { type : "REQUEST_FAILED" , error } ) ;
}
dispatch ( { type : "REQUEST_SUCCEEDED" , payload : response } ) ;
}
}
// redux-recompose example
login : ( authData : AuthData ) => ( {
type : actions . LOGIN ,
target : TARGETS . CURRENT_USER ,
service : AuthService . login ,
payload : authData ,
successSelector : ( ) => null ,
injections : [
withPostFailure ( ( ) => {
//Check the reason of the failure
saveActionToBeSync ( 'login' , [ authData ] ) ;
} )
]
} ) , El primer argumento del método será el nombre que usó antes para declarar las acciones de las secciones en el componente RestoreOfflineActions . El segundo argumento será una variedad de arguments , cuando se restablezca la conexión, se llamará a la associatedAction asociada al name del primer argumento con la lista de argumentos del segundo argumento. Es más simple de lo que parece.
Le recomendamos que tenga un archivo constante donde pueda guardar los nombres de las acciones para que pueda tener esos nombres más organizados, algo así:
// some constant file
export const OFFLINE_ACTION_NAMES = {
SOME_ACTION : "someAction" ,
OTHER_ACTION : "otherAction" ,
} ;Todos los Ocurrencys se eliminarán después de restaurar una conexión y se envían algunas acciones. No es Mather las acciones de algunas secciones no fueron enviadas, de todos modos se eliminarán. Por favor, háganos saber a través de un problema si no está de acuerdo con este comportamiento.
Estas herramientas son una ventaja para esta biblioteca, pero no están relacionadas con la funcionalidad real de esto, podrían ayudarlo a facilitar su trabajo.
Este es un hoc para pedir el estado de la conexión. Aquí hay un ejemplo de uso:
import { withNetInfo } from "sync-offline-actions" ;
class SomeComponent extends Component {
/*some code*/
someMethod = ( ) => {
const { isConnected } = this . props ;
/*Do something*/
} ;
}
export default withNetInfo ( SomeComponent ) ; El PROP isConnected inyectará como un accesorio de SomeComponent debido al HOC WithNetInfo, el PROP se actualizará con los cambios de red.
Esta es una costumbre con la misma funcionalidad de withNetInfo , ejemplo de usar:
import { useNetInfo } from "sync-offline-actions" ;
const SomeFunction = ( ) => {
const isConnected = useNetInfo ( ) ;
// More of the function
} ;Luego, ISConnected se actualizará con los últimos cambios de la conexión.
La gente de @react-native-community/netinfo
git checkout -b my-new-feature )git commit -am 'Add some feature' )git push origin my-new-feature )Este proyecto fue creado por Felipe Rodríguez Esturo. Está mantenido por:
Sync-Offline-Actions está disponible bajo la licencia MIT.
Copyright (c) 2020 Felipe Rodriguez Esturo <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.