I'm building an app using Django - DRF - React through template component invocation. Question is: Whats the right way to pass data from django view-template to react app-component, for example, if the api called in app fetch method used a dynamic parameter:
fetch("/api/endpoint") to fetch("/api/endpoint/modelPrimaryKey")
Sources used:
views.py
def index(request):
return render(request, 'frontend/index.html')
index.html
...
</body>
{% load static %}
<script src="{% static "frontend/main.js" %}"></script>
</html>
main.js (compiled by webpack from this source)
class App extends Component {
constructor(props) {
super(props);
this.state = {
data: [],
loaded: false,
placeholder: "Loading"
};
}
componentDidMount() {
fetch("/api/endpoint")
.then(response => {
if (response.status > 400) {
return this.setState(() => {
return { placeholder: "Something went wrong!" };
});
}
return response.json();
})
.then(data => {
this.setState(() => {
return {
data,
loaded: true
};
});
});
}
render() {
return (
... some jsx
);
}
}
export default App;
const container = document.getElementById("app");
render(<App />, container);