Starting my React Portfolio
So I've mostly finished my portfolio in Blazor (there is a kink to work out with Auth0 and GitHub Pages, but it's mostly there!), and now I'm building a front-end in React. The more I've worked with React so far, the more I've liked it. Being able to isolate your code into components and see your work gradually appear without breaking the rest of your code is satisfying, and while JavaScript sometimes feels like someone spilled a programming language, it's actually very easy to code in. The most challenging aspect of code so far has been getting a list of objects from my API. I say challenging, but once I found the solution it was actually very very easy.
The API call is made easy with Axios, the heavy lifting in on line 7 and 8. We simply reach out to the endpoint and pull the data out of the response. Boom, list of projects. I found that the more complicated part of this came from when I needed to actually display those projects. The asynchronous call made things seem more complicated; should the useEffect be async? Or should the render be asynchronous somehow?
Using React Hooks to handle the state of this component, it's actually just much simpler to create an async function called getProjects() that can try to access the API service and catch any errors. Our function will first display a loading message, and it will try to gather up the project data. When it is successful, it uses a React Hook to set projects and then sets the loading and error hooks to false. In the event that the API call fails, it will display an error message. All of this is called as soon as the page loads, and that extra pair of square brackets is just there to tell useEffect to only run once (so it isn't constantly trying to update the list of projects, causing a weird flicker effect).
You can check out the code here!
Comments
Post a Comment