How to Display quoteText from the response of this API Object - reactjs

Random Quote
How to display the quoteText and quoteAuthor separately from this object for my random quote machine app.I have tried the standard way by writing {this.state.quote.quoteText}.
Here is the response object that I have got from my API.
1:[response object of API]
+Code Snippets
2:[code snippet-1]
3:[code snippet-2]

May be when the component is mounted your data is not yet fetched so here is one possible solution. On line number 37 where you have done this
{this.state.quote !== null && <p>{this.state.quote}</p>}
Instead Try this
this.state.quote.quoteText ? this.state.quote.quoteText : "";
Also on line number 23 where you have done this
axions.get("the url")
.then((res) => { this.setState({
quote: res.data
})
})
Add this line of code
.then((response) => response.json())
so your code will look like this
axions.get("the url")
.then((response) => response.json())
.then((res) => {
this.setState({
quote: res.data
})
})
**Even if that fails try this code that uses fetch **
fetch("the url goes here", {
method: 'GET'
})
.then((response) => response.json())
.then((data) => {
this.setState({
quote: data.response
})
you can call this fetch API directly in componentDidMount() lifecycle .

Related

Express '/' GET request fails, but '/' post, put, delete succeed

I can't figure out what I'm doing wrong here so eyeballs or an idea on how to fix it would be appreciated
Express (4.17.1) + React (17.0.2)
This works fine:
router.get('/test', postListView)
router.post('/', postCreateView)
but this fails:
router.get('/', postListView)
Controllers:
const postListView = async (req, res) => {
// No output from req.method when route is to '/'
console.log(req.method)
res.json({message: 'List View'})
}
const postCreateView = async (req, res) => {
console.log(req.method)
res.json({message: 'Create View'})
}
My POST request React call (works fine):
fetch(`/`,{
method:'POST',
headers:{
'Content-type':'application/json'
},
body: JSON.stringify({title:text.current.value})
})
.then(res => res.json())
.then(data => console.log(data))
.catch(err => console.log(err.message))
GET request that fails:
fetch(`/`)
.then(res => res.json())
.then(data => console.log(data))
.catch(err => console.log(err.message))
Error from GET request:
Unexpected token < in JSON at position 0
I can open the GET request in the browser by going to express directly (localhost:5000).
React is going through a "proxy":"http://127.0.0.1:5000"
I think I'm missing something fundamental with GET requests here but I can't see it so any help or docs would be appreciated.
Thank you,
Since you're using /test as resource path for GET route. Better you use the same route to make the GET request from your react application.
fetch(`/test`)
.then(res => res.json())
.then(data => console.log(data))
.catch(err => console.log(err.message))
For / path, you need to specify which method you're using since you're using same path for both GET and POST request methods.
fetch(`/`, { method:'GET' })
.then(res => res.json())
.then(data => console.log(data))
.catch(err => console.log(err.message))

ReactJS: post request with data through fetch

In my app component, I have state features that contains an array(1500) of arrays(9). I want to send the state (or large array) to my backend so I can run my model and return labels with the following function:
const getLabels = (model) => {
fetch('/spotify/get-labels', {headers: {
'model': model,
'features': features
}})
.then(response => response.json())
.then(data => setLabels(data))
}
However, the response has status 431. This was kinda expected, but I'm not sure how to transmit the data to my backend efficiently. Maybe convert it to json and then put in the headers of my request?
You can try something like this with fetch:
fetch('/spotify/get-labels', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ model, features }),
})
.then((response) => response.json())
.then((data) => {
// Boom!
})
.catch((error) => {
// An error happened!
});
or with axios
axios
.post('/spotify/get-labels', { model, features })
.then((data) => {
// Boom!
})
.catch((error) => {
// An error happened!
});
As far as I'm understanding your concern, I guess passing the 'model': model,'features': features in body should work.
Or using Axios, you can make the request. It exactly like Axios but far better
axios({
url: '/spotify/get-labels',
method: "post",
data: {
'model': model,
'features': features
},
})
.then((response) => response.json())
.then(data => setLabels(data))
.catch((error) => {
console.log("error : ", JSON.parse(error));
});

React JS get data from database using axios.get(url) with param

I'm trying to get data from a database using axios in React. Unfortunately for some reason the url I use doesn't return data although in the browser it does. The url contains a parameter, which is most likely a problem because when I use an url without a parameter, the data is returned.
constructor(props) {
super(props);
this.state = {
userId : this.props.match.params.userId,
users:[]
}
}
componentDidMount() {
const url = "http://localhost:8080/getUser?userId=1";
axios.get("http://localhost:8080/getUser", {params: {
userId: this.state.userId
}})
.then(response => response.data)
.then((data) => {
this.setState({users: data})
});
console.log(this.state.users);
}
Does anyone know how to get database data correctly using REST API and axios?
axios.get("http://localhost:8080/getUser", {
params: {
userId: this.state.userId
}
})
.then(response => response.json()) // You need to parse JSON
.then((data) => {
this.setState({users: data})
});
Only difference is in first .then, you need to parse data to JSON.

fetch api call data is not defined

Hey all I have a react app making a fetch api get request. When I console log the response after turning it into json it works fine but when I try to set state with data it says it is not defined. What am I missing?
componentDidMount() {
fetch('/api/logs')
.then(res => res.json())
// .then(data => console.log(data))
.then(this.setState({ Log: data }))
.catch(error => console.log(error))
}
The second chain expects a callback function, which setState is not.
componentDidMount() {
fetch('/api/logs')
.then(res => res.json())
.then((data) => this.setState({ Log: data })) // <---- wrap setState inside callback
.catch(error => console.log(error))
}

React fetch method is returning json as object rather than array

In my main component, I am fetching the api data and setting it to a state. Rather than an object, I'd prefer it to be in an array. Is there any way I can do this during the fetch and just make the object the first index(and only) index in an array?
fetch('https://api.aes/latest')
.then(response => {
return response.json();
})
.then(json => {
this.setState({
launchData: json,
});
You can use React#spread operator on object.
.then(json => {
this.setState({
launchData: [...json],
});
You might try
fetch('https://api.aes/latest')
.then(response => {
return response.json();
})
.then(json => {
this.setState({
launchData: [json],
});

Resources