Skip to content
Advertisement

How do you filter JSON data using axios and useEffect?

I want to filter the data from this json file:

JavaScript

How can I use axios and React Hooks to filter this data and only get the state name and their actuals as variables to pass in a search UI later?

This is my code currently:

JavaScript

Advertisement

Answer

JavaScript

I’d note that there probably isn’t a reason to try to get rid of the other fields. You could just save the entire response using setData.

After the useEffect runs, data will be filled with an array that you can access in your component.


Update, based on comments:

To filter just one state’s data out, you might do something like this:

JavaScript

Then, you could access the individual properties by doing:

JavaScript

If you wanted to do this while keeping all of the other API data (so that you could change states, for instance, without doing another call, it might look something like this):

JavaScript

Note: I’m not doing any error checking yet for whether [0] exists — you may want to have a case for if the data doesn’t exist

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement