Pages

Showing posts with label react native developer. Show all posts
Showing posts with label react native developer. Show all posts

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.


What are React widgets? | 8 steps to create a custom widget using React.

 What are React widgets?

React widgets are parts that can be added to any React app to make it easier to use, more accessible, and more useful for complex (or simple) forms. These components can be used to create complex user interfaces as well as increase the speed and efficiency of development. There are navigation menus, form elements, data grids, charts, maps, models, and tooltips


All React widgets are designed to be reusable and extensible, making them a great tool for developers who need to create a custom user experience.

 

How to create a custom widget using React?

To begin, create a react app and ensure that you have a supported version of Node.js installed on your computer.


Let's get started by setting up a default React application


Step 1: Setting up a default React application

On your computer, launch a terminal and go to the directory where your app should be.


Type the following three commands:


$ npx create-react-app my-app # create the application named my-app

$ cd my-app

$ npm start # install and run the application

Credits: https://help.ftrack.com/


As soon as you finish typing the above code, you will see the default application running on your computer.

In a browser, navigate to http://localhost:3000/ to confirm that it is operational. 


Edit the App.js file so that it says “My Custom Widget” instead of “Edit src/App.js and save to reload” to make sure it works.


Step 2: Turning the React application into a custom widget

The following criteria must be met in order to create a custom widget:


You have a server somewhere that hosts an application. With a few changes, the standard React server, which can be accessed through port 3000, may be enough for development.


Your app can be shown in an iframe, which is what the create-react-app server does by default. 


The settings on your ftrack workspace allow you to embed applications over HTTPS. The setting controlling this is at System settings > Advanced Settings > Allowed widget URLs.


Step 3: Define the widget's props (properties) by using React's propTypes object.


To define the widget's props (properties), first, you need to import the PropTypes object from the React library.


import PropTypes from 'prop-types';


Then, you can define the props for your React component using the PropTypes object. For example, if you have a component called MyWidget, you could define its props like this:


MyWidget.propTypes = {

  title: PropTypes.string.isRequired,

  description: PropTypes.string,

  size: PropTypes.number,

  onClick: PropTypes.func

};


This defines four props (title, description, size and onClick), with their respective types. The title prop is required, while the other props are optional.


Step 4. Add a render() method that returns the UI of the widget.

Create a class that extends the React.Component class.


Inside the class, define a method called render() that returns the UI of the widget then create the JSX code that will represent the UI of the widget.



Step 5. Use the componentDidMount() method to fetch any necessary data.

return (

  <div className="App">

    <header className="App-header">{session.apiUser}</header>

    <main>

      <ul>

        {projects.map((project) => (

          <li

            onClick={() => {

              displayProjectInfo(project.id);

            }}

          >

            {project.name}

          </li>

        ))}

      </ul>

    </main>

  </div>

);


Step 6: Add any methods you need to add interactivity to the widget.


Step 7: Wrap the widget in a Higher Order Component (HOC) to give it access to any global state or functions it may need.


Step 8: Finally, return the JSX code from the render() method and export the component so it can be imported and used in other parts of the application. 4. Finally, return the JSX code from the render() method.


Final Thought: 

The aforementioned steps will help you create a custom widget using React. However, if you want a professional app then it would be best to hire react developers from Adequate Infosoft to get quality services. Adequate Infosoft is the industry leader in React.js app development, and we will help you to create effective, engaging apps that contribute to the expansion of your business. 


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...