Created
March 31, 2018 02:57
-
-
Save thequbit/b0fc7a025d98414e2d291e8ed33648b2 to your computer and use it in GitHub Desktop.
json contents replace help
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
You currently have ... | |
componentDidMount() { | |
fetch(API).then( | |
response => response.json() | |
).then( | |
data => this.setState( | |
{ | |
quotes: data | |
} | |
) | |
); | |
} | |
So the fetch(API).then() returns the json, and thus becomes a | |
javascript object. We know the json looks like this: | |
{ | |
ID:1283, | |
content: "<p>Be a first rate version of yourself, not a second rate version of someone else. </p>\n", | |
link: "https://quotesondesign.com/judy-garland/ ", | |
title: "Judy Garland" | |
} | |
So what we'd like to do, is take the json response from API, | |
and manipulate it before sending it along ans the return to | |
the next promise. | |
So we know that the () are optional in the => syntax, so | |
response in the first then is the param that is passed in | |
the function. So we can do this: | |
fetch(API).then( | |
response => { | |
response = pre_process_json( response.json() ) | |
} | |
).then( | |
data => this.setState( | |
{ | |
quotes: data | |
} | |
) | |
); | |
} | |
pre_process_json() is a function that we'll need to write, | |
that will remove the <p> from the response. | |
Alternatively, we could implement the .replace() where | |
the quotes field within data is being consumed ( which | |
really is much simpler ) | |
https://github.com/manAbl/random-quotes-machine/blob/master/src/components/QuoteMachine.js#L27 | |
So you would change the quote update to: | |
return ( | |
<div className="app-wrapper"> | |
{ quotes.map( quote => | |
<blockquote> | |
{quote.content.replace(/<\/?[^>]+(>|$)/g, "")} | |
<label htmlFor="author">- <span>{quote.title}</span></label> | |
</blockquote> | |
)} | |
<i className="twitter fab fa-twitter"></i> | |
<button >Get Random</button> | |
</div> | |
) | |
} | |
where ... | |
{quote.content.replace(/<\/?[^>]+(>|$)/g, "")} | |
... being the key part. You're in an interator that is | |
taking the array of quotes from the API reponse, and | |
generating a quote. The quote has a field called contents | |
that you are displaying. You can just apply the replace() | |
regex that I linked to to the contents filed right inside | |
the html. | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment