Redux with typescript
Meet Vaghasiya
Passionate Vue.js & Laravel Developer | JavaScript Lover | Eager to Learn
Let's see how we use redux with typescript
npx create-react-app typescript-practise --template typescript
3. Install redux, react-redux, redux-thunk, and Axios.
npm i?redux react-redux axios redux-thunk
4. make a reducers folder and configure it in a reducer/index.tsx file.
so now we have our basic typescript set with reducer and app component. make sure you don't have any errors in the console.
5. so now make an actions folder and create an index.ts file. note that here and in the reducers directory we create an index.ts file. because we do not require Html code in that.
write the below code in the actions/index.ts file.
Did you notice something? here we do not use many typescripts but typescripts will not give errors. typescript will take the type of payload as ANY . which is not good. so let's fix this. also here FETCH_TODO is static. so something may make a type. so let's create an enum for that.
So create a types.ts file in actions and define fetchTodo there in the enum. so we do not accidentally use this key in a different place and also avoid typos.
We also need to pass API data response type in axios.get<Todo[]> request as generics as shown below. so now if you hover on payload,then it will take type as Todo[] .
But here we send payload ="anything", it will not give an error. typescript inference type as a string. so if we strictly want that payload in dispatch be Todo[] only. then we pass on use of generics here.
So now let's create todoReducer. so make a file in todo in the reducers directory.
Now make changes in the reducers/index.ts file.
If we pass another function by mistake then todoReducer, then it will not give an error. like,
So we need to pass generics in combineReducers, to avoid this type of issue. So make interface StoreState, and pass as generics. another benefit is any developer understands StoreState
领英推荐
So, let's connect our redux with App.tsx . follow some steps as mentioned below.
Listing of todo
Here we will make a button, and if users click on that button, then after todo will be fetched.
Deleting todo
But currently, you will get an error in connect function, because in AppProps fetch too is redux-thunk, and todo will return an object. typescript will think both types is different. so change the type of fetchTodo to Function.
So now, our todo works fine using typescrpit and redux. That's it for the day guys........