Let's talk about state management common abuse. We choose our favorite state management tool, connect components to backend API functionality, and start using state management awesomeness. I created a React application, declared an API function called fetchPokemon, and used a Pokemon API service to fetch relevant data. I added a two-second delay, fetched the data, and implemented the UI to display the Pokemon data and a button to fetch random Pokemon. Finally, I added some styling to the UI.
Enough about me, let's talk about state management common abuse. So we've all been there, starting a React application, choosing our favorite state management tool, like Redux or Morbix, or many others out there, and connecting our components using these tools to our backend API functionality and start using state management awesomeness.
Let's see it in action. I created a simple React application using code sandbox, and I'll start by declaring an API function called fetchPokemon, which will get in the parameters the Pokemon name, and we will use a Pokemon API service to fetch the relevant Pokemon data. I wrapped it with a promise to make sure we get some delay in the response to mock a common behavior of API functions. So there's a setTimeout, and I set it later to two seconds of delay.
Now I'll do the fetching. We have the Pokemon name, handle the response, which is in a JSON format, so I'll use the JSON, and return the data. Cool. Great. Let's add the two seconds delay I talked about, and now I can call the endpoint in the UI, declaring the state PokemonData and setPokemonData using the useState hook, and creating a fetch random Pokemon function so the app won't be boring.
So I'll be using or I'll be choosing out of three common Pokemons, Pikachu, Charizard, and Squirtle. We will use some random logic using the math library, so multiplying math random with the array length minus 1 and round it up. And now I can use it. I'm calling the fetchPokemon with the chosen Pokemon name. Cool. Return the data. Great. And now for the best part, the UI. So I will declare a div container and display the Pokemon data in a div and create a button for using the fetch function. So in the div, I will display the Pokemon name as well as its image using the sprites data which we get from the Service API. Put it in the image source. And great! Back to the button. I will attach the fetch random Pokemon, which we implemented. And let's add some text. And let's add some alternative text to remove the annoying warning of the Kot Sandbox. Add some typo here. And test it. Cool! We've got Squidward. Now let's add some style, just to move the text a little bit up above.
Comments