Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Pierre Smith
Pierre Smith
11,842 Points

Using Axios with Redux

I trying to build an app that gets related data to what the user types from an API I built and displays it.

I have an action that gets passed the string from the textbox.

Now I'm wondering if I should be doing the fetch call inside of the reducer, and if so how would I create a new state once I get the data, because every time I try to log the data from outside of the fetch it logs undefined which is probably because of the fact that axios is asynchronous.

Basically, I want to know how do I return a new state from within a switch statement with the data fetched by axios. AND should I be making the call from within the reducer or should I make the call in the container and pass the data to the reducer.

1 Answer

Seth Kroger
Seth Kroger
56,413 Points

There's an entire workshop on that topic that's also part of the Learn React track: https://teamtreehouse.com/library/data-fetching-in-react It covers both fetch and Axios.

You wouldn't put the calls into a reducer because the reducers are supposed to be pure functions (i.e., their returns are solely based on the arguments you pass in), Relying on an external source that can change over time makes them impure. You'd also be stalling the reducer waiting for the API to return a new state, and you'd have little to no control over how often the API requests are made.