3.8 CORS and async/await in react

2h Tonight my whole fam has the flu, so it’s been challenging. I was able to find some interesting things to fix on my craigslist scraper. I’m starting to separate the express side from the react side and it’s fun to see how they are similar and different. My first issue was called a CORS issue, and it relates to client side js not being able to be called from another domain. This is due to a lot of security threats, and serendipitously I listened to a syntax podcast all about CORS today. Dang those guys are nice and good. I then found a site showing how to set up express with a npm repo called ‘cors’ and away I went!

After that I really struggled trying to figure out how to deal with the data on the react side. I didn’t do it exactly as I did on the express side because I couldn’t see a use case for an object. Specifically it would have involved me sorting data from a json file to pass it into an object constructor so that I could call a method on that object that returns formatted html. Since this is react I could skip a few steps and just make a method to process the json entries directly. That’s what I did – but I’m getting ahead of myself. My big issue was trying to deal with the data from the promise in react. It took a lot of googling, but eventually I figured out that you need to call response.json() in order to treat the response as json BUT that also creates another promise! So you need a .then statement after you return the response.json() that will contain the data you so eagerly await.

One other related thing is where to put this async call. I read that it is best in componentDidMount and it is definitely working there. Currently I have a static search running and saving it to state. Then I have a function call inside of the return that parses the state and generates divs. I’m not sure if that will change once I’m passing in user generated search terms, but it seems like a similar function running in componentWillReceiveProps could work out well as well. In the future I should be able to pass in search terms and cities to this component and it will return the content! One thing I havent implemented yet is the blocking/hiding feature. I could keep that contained to this component and persisted in localstorage. My one big idea is that I want to be able to set up alerts that text you when a new item is found. I would want that alert to obey your client side blocks, so I need to find a good way to mirror the blocks onto the server.

Tell me what you think.

This site uses Akismet to reduce spam. Learn how your comment data is processed.