Pages

How to access the state using Redux RTK in react native app

 How to access the state using Redux RTK in React native app?

In our previous blogs, we have learned to create a simple app with React.js, replacing redux with the help of the react hook, and many other things. Now it's time to move ahead and learn something new. In today’s article, we will access the state using Redux RTK.


To get started, we have to install the Redux Toolkit package. In our previous blogs, we detailed the entire installation process for Redux Toolkit. But, since we want to share complete information with our novice React developers, let's start from scratch.


Step 1: Install the Redux Toolkit package

First of all, we have to install Redux Toolkit and React-redux within the project.


As Redux Toolkit is already installed in the project in Typescript format, we have to install react-Redux using the below command:



# NPM

npm install @reduxjs/toolkit react-redux

# Yarn

yarn add @reduxjs/toolkit react-redux



React Redux has a dependency on @types/react-redux so the type definition file of the package will be automatically installed with it.


Step 2: Create an API with customBaseQuery

As we are using Redux RTK queries in our React Native project, we can't figure out how to access the state without firing the query each time. So, it is mandatory to create an API with customBaseQuery using the below command.



const emptySplitApi = createApi({

  reducerPath: 'api',

  baseQuery: customBaseQuery(),

  endpoints: () => ({})

})



Step 3: Inject endpoints

The next step after creating APIs is to inject endpoints. You can insert endpoints in your application by the below written command. 



export const userApi = emptySplitApi.injectEndpoints({

  endpoints: (builder) => ({

    getUser: builder.query<User, GetUserInput>({

      query: (options) => ({

        query: getUserQuery,

        options: options

      })

    })

  }),

  overrideExisting: true

})



Step 4: Configure the Store:

It's quite simple to configure the store in a React native app, and you can do it by following these steps. Initially, you have to create a store folder and then create an index.js file in the store folder. After that, use connect() to link the components to the store and send the actions to the store to change it.



const persistConfig = {

  key: 'root',

  storage: AsyncStorage

}


const reducers = combineReducers({

  [emptySplitApi.reducerPath]: emptySplitApi.reducer

})


const persistedReducer = persistReducer(persistConfig, reducers)


export const store = configureStore({

  reducer: persistedReducer,

  middleware: (getDefaultMiddleware) => getDefaultMiddleware({ serializableCheck: false }).concat(emptySplitApi.middleware)

})



Step 5: Using Dispatch Hook

You can also use the Redux RTK useDispatch hook to send actions that change the state. Here is the command to use useDispatch:



import { useDispatch } from '@reduxjs/toolkit';


const MyComponent = () => {

  const dispatch = useDispatch();


  const addTodo = () => {

    dispatch({

      type: 'ADD_TODO',

      payload: {

        "My new to-do," text

    });

  };


  return (

    <View>

      <Button onPress={addTodo} title="Add Todo" />

    </View>

  );

};



Lastly, we have to make a call to the getUser API through the redux-generated hook whenever the application is opened. This is effective, and we will get the desired response.



const { data } = useGetUserQuery(input)



Now, we need to access the user data on another screen of our app without calling the API again (Redux should have cached or saved the data). 


Final thoughts

In conclusion, Redux RTK is the best tool that can be used to easily access the state of your React Native app. It is a great alternative to building a custom Redux store that can help you keep your codebase cleaner and more organized. With Redux RTK, you can access the state of your React Native app with ease, allowing you to quickly access the data you need.


No comments:

Post a Comment

Make new Model/Controller/Migration in Laravel

  In this article, we have included steps to create a model and controller or resource controller with the help of command line(CLI). Here w...