I am trying to use ReactJS to build a simple website that pulls data from my Django REST Framework API. The issue I am running into, is that my data is not being output by React. I am certain that my Django backend is running flawlessly. I get no errors when running it, and can view my API data via "http://127.0.0.1:8000/api/".
Here is my frontend ReactJS code:
import React, { Component } from 'react';
class App extends Component {
state = {
usernames : []
};
async componentDidMount() {
try {
const res = await fetch('http://127.0.0.1:8000/api/');
const usernames = await res.json();
this.setState({
usernames
});
} catch (e) {
console.log(e);
}
}
render() {
return(
<div>
{this.state.usernames.map(item => (
<div key={item.id}>
<h1>{item.username}</h1>
</div>
))}
</div>
);
}
}
export default App
I have tried updated my CORS_ORIGIN_WHITELIST via settings.py and includes all variations of localhost.
When scripting with Python, I am able to make a request and retrieve my API data. This is the output:
[{'username': 'testname', 'created_at': '2019-12-06T00:03:50.833429Z'}, {'username': 'testname2', 'created_at': '2019-12-06T00:04:01.906974Z'}, {'username': 'testname3', 'created_at': '2019-12-06T00:04:05.330933Z'}, {'username': 'testname4', 'created_at': '2019-12-06T00:04:08.144381Z'}]
And though no ID is present in the output (Which I'm not sure why) I can still access the correct data by making a request like this: "http://127.0.0.1:8000/api/3/"
Any help is appreciated.
item.idreference since you already know it's not in your JSON object?Access-Control-Allow-Origin: *just for the purposes of local development? Obviously, you don't want to do that in general, but doing it on your local machine while you're dev'ing is fine. See here if you are unsure of how to: techiediaries.com/django-cors