fetch api call data is not defined - reactjs

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))
}

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))

unable to read response object on react

My django api responds with the username if the user is authenticated and a not authenticated details msg if not authenticated
but i am unable to read the status code or console log or catch the 401 status code and res.status gives undefined msg
console img
how can i use http status to render depending on the code received .
export default class GetUser extends Component {.....}
componentDidMount(){
fetch("http://127.0.0.1:8000/app/ebooks/",
{ CSRF_TOKEN.....
},
})
.then(res => res.json())
.then(res => {
this.setState({data:[res]})
console.log(resp.status) --->UNDIFINED
})
.catch(err => console.log(err));
}
render() {
var x = this.state.data
return (
<pre>{JSON.stringify(x, null, 2) }</pre>
)
}
}
Move the console.log() up to the first then clause.
.then(response => {
console.log(response.status) --> 401
return response.json()
})
.then(data => {
this.setState({data:[data]})
})
.catch(err => console.log(err));

Axios not working properly when using window.location.href to redirect page in react

I'm using axios to send requests to my server. Now I wanted to apply redirects in my frontend(React) using the window.location.href property. But the axios request is not being sent. I also tried to carry out an axios request and reload the page and it doesn't work even then.
axios.post("/api/orders",params)
.then(res => {
console.log("Order Placed");
axios.delete("/api/cart/"+user_id)
.then(res => {
console.log("Cart Deleted");
})
.then(res => {
window.location.href = '/myOrders';
})
.catch(err => {
console.log(err);
})
})
.catch(err => {
console.log(err);
});
Here the axios.post works but the axios.delete does not. The page is getting redirected.
In the next code, again the axios.delete does not work.
axios.get('/api/getuser/')
.then(res => {
user_id = res.data.id;
console.log("Id Received");
})
.then(res => {
axios.delete("/api/cart/" + user_id + '/' + this.props.id)
.then(res => {
console.log("Product Deleted");
})
.then(res => {
window.location.href = '/cart';
})
.catch(err => {
console.log(err);
})
})
.catch(err => {
console.log(err);
});
Can someone please point out what the issue is or suggest a work-around?
It worked when I put the redirection statement in the first then function itself. It seems all the thens are triggered simultaneously. Because of this, the second then was triggered before the first.

How to Display quoteText from the response of this API Object

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 .

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