1.

What is the use of middleware Redux thunk?

Answer»

Redux thunk is a middleware which sits between action creator and reducer in the React-Redux flow. It is very USEFUL when we do asynchronous API calls with FETCH or axios, which returns a Promise and we then dispatch it to reducer.

Redux thunk mainly works behind the scene. We have used some boiler-plate to use it.

//App.js IMPORT React from 'react'; import ReactDOM from 'react-dom'; import Routes from './routes'; import STORE from './store'; import { Provider } from 'react-redux'; ReactDOM.render(    <Provider store={ store }>        <Routes />    </Provider>,  document.getElementById('root') ); //store.js import { createStore, applyMiddleware } from 'redux'; import thunk from 'redux-thunk'; import rootReducer from '../reducer'; const store = createStore(rootReducer, applyMiddleware(thunk)); export default store;

In Question 22 for React-Redux flow, in action creator, we call an API endpoint with axios. It is a network request and will take some MILLISECONDS or more depending on the connection.

Now, thunk middleware sort of wait for that call, which is a Promise to completed. Once we get the response, which contains the data then only it dispatches it to the reducer.

export const getIndPopData = (currYear) => dispatch => {    return axios.get(`http://api.population.io:80/1.0/population/${currYear}/India/`).then(response => {      dispatch({ type: GET_INDIA_DATA, indPopData: response.data });    }); };

So, Redux thunk is required in Projects where we do API calls to some endpoint.



Discussion

No Comment Found