One of the popular state management tools out there is Redux.
Setting up a Typescript React Native Project with Redux can be tricky for beginners, in this article, I will teach you how you can easily get started.
I am assuming, you have a React Native Typescript Project setup, if you don't, you can run this command:
npx react-native init ProjectName --template react-native-template-typescript
Your project will automatically be bootstrapped with typescript template.
Installing dependencies
I like using yarn, but you can also use npm
yarn add redux react-redux redux-thunk
Afterwards, let's install redux type definitions
yarn add @types/react-redux -D
Create a new folder call "Store".
You can name the folder as you desire, but I prefer to use store.
Inside this folder, create three folders:
- actions
- reducers
- types
and lastly, create an index.tsx file.
In your index.tsx file, paste the following code
import { createStore, applyMiddleware } from 'redux'; import thunk from 'redux-thunk'; import appReducer from './reducers'; export default createStore(appReducer, applyMiddleware(thunk));
The next action is to define your Types.
In your types folder, create an index.tsx file and paste the following code
export const USER_TODO = 'USER_TODO';
Save and close.
Next stop is the actions folder, for this folder, I like to create an index.tsx file and other actions. So if you are creating a big application, you might have something like this
index.tsx
users.tsx
admin.tsx
payment.tsx etc.
This makes your file structure cleaner and more understandable.
But for this simple application, we will be needing just two files:
index.tsx and
todo.tsx
Inside your index.tsx file, paste the code below:
import todoAction from './todo'; export { todoAction };
Save and Close
In your todo.tsx file, you will define how your actions are to look like,
First import all your types
import { USER_TODO, } from '../types';
Then set up your actions
const setUserTodo = (payload: number) => ({ type: USER_TODO, payload, }); export default { setUserTodo, };
Save and Close.
Lastly, create two files in your reducers folder
index.tsx and
`
todo.tsx
inside your todo.tsx file, paste the following code:
import { USER_TODO } from '../types'; const initialstate = { userTodo: [], }; type Action = { type: string, payload?: any } export default (state: any = initialstate, action: Action) => { switch (action.type) { case USER_TODO: return Object.assign({}, state, { userTodo: action.payload, }); default: return state; } };
inside your index.tsx file, paste the following code:
import { combineReducers } from 'redux'; import todo from './todo'; const appReducer = combineReducers({ todo, }); export default appReducer; export type State = ReturnType
And that's it! You have successfully set up your redux store, now let's head over to the UI part.
I will make use of JSON public placeholder API to generate list of todos
https://jsonplaceholder.typicode.com/todos/
You can use the useDispatch
hooks from react-redux to easily dispatch data into your reducers
In your App.tsx, paste the following code:
import * as React from 'react'; import { Text, View, StyleSheet } from 'react-native'; import { useDispatch } from 'react-redux'; import { todoAction } from '../store/actions'; interface AppProps { navigation: any; setTodo: any; } const Welcome: React.FC = ({ navigation: { navigate } }) => { const dispatch = useDispatch(); React.useEffect(() => { loadTodos(); }, []); const loadTrivia = () => { try { const response = await fetch( 'https://jsonplaceholder.typicode.com/todos/' ); const json = await response.json(); dispatch(todoAction.setUserTodo(json)); } catch (error) { console.error(error); } }; return ( < View style={styles.container}> < /View> ); }; export default App;
And to get the list of these todo, use useSelector
hooks from react-redux
import React from 'react'; import { View, Text } from 'react-native'; import { useSelector } from 'react-redux'; interface TodoProps { navigation: any; } const Todo = (props: TodoProps) => { const { userTodo } = useSelector((state: State) => state.todo); const TodoList = ({data}) => { return ( < View> < Text>{data.title} < /Text> < /View> )}; return ( < FlatList data={userTodo} renderItem={({ item }) => } /> )}; export default Todo;
And that is it!
That is the simple way to easily add redux to your React Native Typescript project.
Let me know if you have any questions!
Top comments (2)
Great beginner tutorial! However I'm getting a TypeScript error on reducers/index.tsx saying "Generic type 'ReturnType' requires 1 type argument(s)". Any idea how to fix it?
export type RootState = ReturnType<typeof appReducer>;