This is a demonstration of the redux thunk
middleware in a single JS file. The middleware is added to store, so that we can perform asynchronous operations such as API calls.
This project explains the core concepts of Redux in a short and concise manner.
- Go to directory:
cd redux-demo
- Install axios and redux libraries:
npm install
- Fetch JSON example using action creator:
node ./asyncActions.js
This is a demonstration of the redux thunk
middleware in a React project. The concepts in redux-demo
apply here as well.
- Reducer is defined in
userReducer.js
and returns an updated state given the previous state and an action. It's used in the createStore method instore.js
and is defined as a pure function, meaning no side-effects such as API calls are permitted. - Action creator
fetchUsers()
is defined inUsersActions.js
and is able to do API calls. An Action is an object that represents change of state and needs to be dispatched to the store to trigger state changes. fetchUsers()
is an async action (API call) and is invoked once the React ComponentUsersContainer.js
is loaded.UsersContainer.js
is subscribed tostore
, because it is wrapped inside Provider inApp.js
and uses theconnect()
function. It also maps the state to props, so the fetch data can be consumed by the component for use in the DOM.
- Go to directory:
cd react-redux-demo
- Install axios, react and redux libraries:
npm install
- Deploy locally to see thunk allowing API call on action:
npm run start
In userReducer.js, the response is going through a switch function
This is a demonstration of the redux thunk
middleware in a React project with Typescript and Redux-Toolkit (RTK).
Works similarly to react-redux-demo
, but uses the RTK library:
UsersSlice.ts
: Here we create our reducerusersSlice
and async actiongetUsers
.store\index.ts
: We create the store usingconfigureStore
.
- Go to directory:
cd ts-react-redux-demo
- Install axios, react, redux, RTK and typescript libraries:
npm install
- Deploy locally to see thunk allowing API call on action:
npm run start