I try to construct an application using React so in the principal folder named “App” exactly in “App.js” file in the constructor method in the “state.text” I try to assign the text state a random quote text by declaring a static method to get an API response quote within the class “App” but my app doesn’t work as I expect so this is my code :
this is the App.js file :
import React from "react";
import './App.css';
import Text from '../Text/Text';
import getQuote from '../../helpers/RandomQuote'
class App extends React.Component {
constructor(props) {
super(props)
this.state = {
text: getQuote.text,
author: getQuote.author
}
}
render() {
return (
<div id="quote-box" >
<h1> My quote</h1>
<Text text={this.state.text} />
{/* <Author />*/}
{/*<Button />*/}
<a href="https://twitter.com/intent/tweet">Tweet</a>
</div>
)
}
}
this is the RandomQuote.js file:
const getQuote = function() {
let text;
let author
return fetch('https://type.fit/api/quotes',{method: 'GET'}).then(response=> {
if(!response.ok) {
throw Error(response.status)
}
return response
})
.then(response=> {
return response.json()
}).then(jsonResponse=> {
const quotes = jsonResponse;
let indexQuote = Math.floor(Math.random() * quotes.length);
const quote = quotes[indexQuote];
return quote
}).then(quote=> {
return {
text: quote.text,
author: quote.author
}
})
}