encryption storage for React Native with TypeScript and Redux

// store.ts

export const createAppReducer = () =>
  combineReducers({
    system: systemReducer,
    posts: postsReducer,
  });

const reducer = createAppReducer();
export type RootState = ReturnType<typeof reducer>;

export const createAppStore = (initialState?: Partial<RootState>) =>
  configureStore({
    reducer,
    preloadedState: initialState,
  });

// utils.ts

import EncryptedStorage from 'react-native-encrypted-storage';

export const getStateFromAsyncStorage = () => {
  async function retrieveUserSession() {
    try {
      const session = await EncryptedStorage.getItem('user_session');
      if (!!session) {
        return {
          system: {
            userId: JSON.parse(session).userId,
            accessToken: JSON.parse(session).bmAccessToken,
            refreshToken: JSON.parse(session).bmRefreshToken,
          },
        };
      }
    } catch (error) {
      console.log(error);
    }
    return {}
  }

  const res = retrieveUserSession()

  return res;
};

// App.tsx

const state = getStateFromAsyncStorage()

const store = createAppStore(state);

const Stack = createNativeStackNavigator();


const App = () => {
  return (
    <Provider store={store}>
      <NavigationContainer>
        <AuthStack />
      </NavigationContainer>
    </Provider>
  )
}

export default App;

I am facing an issue where I cannot pass the state variable to the create App Store function, as getStateFromAsyncStorage() returns a Promise. How can I ensure that the Partial type is preserved in state after calling getStateFromAsyncStorage()? Alternatively, can someone suggest a method to securely store JWT tokens in React Native?

Answer №1

To properly utilize the Promise returning method, make sure to incorporate the async and await keywords.

If you want to manage the Promise generated by an async function, remember to employ the await keyword when invoking it.
Below is an example demonstrating how you can use getStateFromAsyncStorage() with async and await:

App.tsx:

// Don't forget to include necessary imports

const Stack = createNativeStackNavigator();

const App = () => {
  const [store, setStore] = useState(null);
  useEffect(() => {
    async function initializeStore() {
      try {
        const state = await getStateFromAsyncStorage(); // Utilize await to handle the Promise
        const appStore = createAppStore(state);
        setStore(appStore);
      } catch (error) {
        console.error(error);
      }
    }
    initializeStore();
  }, []);

  if (!store) {
    return null;
  }

  return (
    <Provider store={store}>
      <NavigationContainer>
        <AuthStack />
      </NavigationContainer>
    </Provider>
  );
}

export default App;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Create objects in the gallery

I recently developed a React Material-UI component using Typescript: <Grid container direction="row" justifyContent="flex-start" alignItems="flex-start"> <Grid item xs={5}> <B ...

Tips for creating a linear gradient effect on Instagram stories using React Native

I'm trying to achieve a similar effect to the example below without using animation, but I'm having some trouble. Here's my component and what I have so far: Desired Outcome: https://i.sstatic.net/7zwq6.jpg Code Snippet: <LinearGr ...

What's the best way for me to figure out whether type T is implementing an interface?

Is it possible to set a default value for the identifier property in TypeScript based on whether the type extends from Entity or not? Here's an example of what I'm trying to achieve: export interface Entity { id: number; // ... } @Compon ...

What is the method to update reference models in mongodb by generating documents within a different model?

In my API, I have three models: Patient, Doctor, and Reviews. The Reviews model is referenced in the Doctor model, with the intention that a patient can post a review for a specific doctor using Review.create(). However, even after the review document is c ...

When I try to run eas, I encounter the following error message: "zsh: command not found: eas"

Have you ever encountered this issue before? It was a bit of a challenge for me to resolve, so I'm curious if anyone else has any insight on how to fix it. Please feel free to share your solutions below! ...

Icon Stacking - overlaying icons on top of one another

I recently implemented a Google map in my React Native app. However, I'm facing an issue where the icons on the map are overlapping each other instead of being positioned on either side. Despite trying various configurations, the result remains unchan ...

Dealing with a reduction in a union type: pointers and advice

I am encountering an issue with the code snippet below: (TS Playground link) type TDeliveriesStatsDatum<TName = string> = {name: TName; value: number}; type TDeliveriesStatsData<TName = string> = TDeliveriesStatsDatum<TName>[]; interface ...

Retaining previous versions with Cloud Run caching

Despite deploying a new version of our code to the cloud run instance, some users are still accessing the older revision. Even after closing their window or refreshing the page, the issue persists. Our cloud run instance operates on JavaScript React Redux ...

Adding a dynamic CSS stylesheet at runtime with the power of Angular and Ionic 2

Currently, I am working on creating a bilingual application using Ionic2. The two languages supported are English and Arabic. As part of this project, I have created separate CSS files for each language - english.css and arabic.css. In order to switch be ...

Unusual behavior and confusion encountered with loadChildren in Angular 7 routing

I've encountered a strange behavior while using loadChildren in my application and I'm quite confused about why it's happening. Here is the content of my app-routing-module.ts: const routes: Routes = [ { path: '', redire ...

The data type 'AbstractControl | null' cannot be assigned to type 'FormGroup'

I am facing an issue with passing the [formGroup] to child components in Angular. The error message says Type 'AbstractControl | null' is not assignable to type 'FormGroup'. I have double-checked my conditions and initialization, but I ...

What is the significance of default parameters in a JavaScript IIFE within a TypeScript module?

If I were to create a basic TypeScript module called test, it would appear as follows: module test { export class MyTest { name = "hello"; } } The resulting JavaScript generates an IIFE structured like this: var test; (function (test) { ...

TSC is unavailable - Unable to read file named "anything.ts": File is missing

I have been facing a frustrating issue with the TSC Typescript compiler. No matter what I try, I cannot seem to make it find any files. I have experimented with both the tsc provided by the Visual Studio Extension and the one from npm. I've attempted ...

Is it possible to access the passed arguments in the test description using jest-each?

Utilizing TypeScript and Jest, consider this sample test which can be found at https://jestjs.io/docs/api#testeachtablename-fn-timeout it.each([ { numbers: [1, 2, 3] }, { numbers: [4, 5, 6] } ])('Test case %#: Amount is $numbers.length =&g ...

Encountering a type discrepancy issue when attempting to send a message to the SQS queue

Encountering a type mismatch error while attempting to send a message to the SQS queue using the documentation found at https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/javascript_sqs_code_examples.html. I have provided package details and ...

Linking up Redux devtools and Thunk middleware with the store

I've been working on connecting redux-devtools to my store, but I'm running into an error that says: "It looks like you are passing several store enhancers to createStore(). This is not supported. Instead, compose them together into a single func ...

While working with Ngrx/effects, an error with code TS2345 occurred. The error message stated that the argument is of type 'Product[]', which cannot be assigned to a parameter of type

When I compile my code, I encounter the following issue (despite not finding any errors in the browser console and the application functioning properly). An error occurs in src/app/services/product.service.ts(15,9): The type 'Observable<Product> ...

What are the steps to customize the date pipe in Angular?

Encountered the InvalidPipeArgument issue with Safari for date/time format, but managed to resolve it by following the solution provided in this Stack Overflow thread. Currently using: <mat-cell *cdkCellDef="let payroll" fxFlex="20%"> {{payroll.tim ...

Understanding how to infer type from the arguments of a class constructor in Typescript

Is there a way to reuse the argument type definition of a class constructor without refactoring or extracting it from the class itself? I have tried using GetProps<TBase>, but it doesn't work as expected. In the example below, the const bp defin ...

Issue encountered in Ionic/React/Typescript - Incorrect props supplied to React.FC<'erroneous props provided here'>

Having struggled with this issue for a while now without any success, I have searched through numerous questions here but none seem to address my specific case. Therefore, I kindly request your assistance. I am encountering difficulties passing props thro ...