Quick Guide for Fetching API Data Using React Redux and Hooks(with Examples)

Javaria Brascom
Feb 2 · 4 min read

Checklist:

  1. Why Redux?

So, Why Redux?

It is typical in React to use a class component to declare your applications state, passing this down to each child component individually. As straight forward as this may be, it will take a profuse amount of planning ahead to minimize your time spent restructuring and and fixing bad practices in your app.

Left: Regular State Hierarchy Right: How redux helps

In the figure above, state is normally passed from top to bottom while Redux allows you to have a direct relationship. It does so by saving your state in a “Store” that you can access regardless of where you are in your application.

Example: Normal Fetching in Class Component

Fetching Data:

This method requires a class component where you will define your state as an object, fetch the data after the component mounts, and directly pass down this.state.data to its children components.

Accessing Fetched Data in Child Component:

Our function component then has to access its own properties (props) to display the passed data.

Example: Fetching in Functional Component using Hooks and Redux

Fetching Data in Redux:

Instead of ComponentDidMount we will fetch inside of our useEffect Hook(think of this hook as componentDidMount, componentDidUpdate, and componentWillUnmount combined.) Our dispatch Hook then sends our new state of tasks from our API to our Store (we will talk about this in a second).

Accessing Data in Redux:

When accessing data we saved from the API, we will need help from the useSelector Hook. We verify which part of state we want our Selector Hook to obtain, and then set it to a variable in order to access and manipulate later in the component.

Breaking it all down: Provider and the “Store”

In the Fetch example we dispatched our api data and selected it using hooks. In order for each of these to work we will need to create a redux store and use it in our Provider wrapper. The store contains a tree of all the state in our application and our Provider tag is the bridge that gives our application access to this store.

Syntax:


import { createStore } from 'redux' //holds our state
import { Provider} from 'react-redux' //allows us to access and handle store/stateimport reducers from './reducers'
export default function App() {
const store = createStore(reducers) //imported above return (
<Provider store={store} > //takes in argument of our store
<ExampleComponent /> //anything here has access to our store
</Provider>
)
}

As you see our store takes in an argument for imported reducers that allow us to manipulate and change this state. Anything wrapped in the Provider tag will have access to our store.

Reducers- Dispatch’s Significant Other

Example 1:

const stateReducer = (currentState, action)=> { //dictate what newState returnsreturn newState}

Example 2:

const counterReducer = (phrase, action) => {    if (action.type === 'SAY_HI') {       return "Hiiiii";    }    if (action.type === 'SAY_BYE') {        return "Byeee";    }    return phrase;};.

Reducers are pure functions(functions that return the same value without changing global variables or modifying its arguments) that use their action argument to dictate their return value. In the case of controlling state, we are able to use our dispatch hook to request data, but they need to have matching type keys in order for the reducer to provide the correct information.

A Typical Dispatch/Reducer Relationship:

Dispatch Function and Objectimport {useDispatch} from 'react-redux'; const dispatch = useDispatch();dispatch({type: "SET_TASKS", todo: tasks})) // tasks = fetched api data you are sending to your redux methodOur Reducer method would look something like:const taskReducer = (state=[], action) =>{
switch(action.type){
case "SET_TASKS":
return action.todo
default:
return state
}

In this scenario we are using the dispatch function, imported from redux, to send an action to the taskReducer. The task reducer then verifies the objects type key before returning the specified value or the default value in the opposite case. Referencing the fetch example above, the reducer will return an array of tasks or the empty array we set to “state”.

Key Note: do not continue to use switch-case statements if you can separate it into an entirely different reducer function.

Conclusion:

Now that you have a better understating React Hooks and Redux, hopefully you have a new way to manage your state. If you would like to reach me please do so here: www.linkedin.com/in/javaria-brascom-0510991bb or at javariab17@gmail.com.

The Startup

Get smarter at building your thing. Join The Startup’s +741K followers.