I'm trying to get information from the API based on information I'm sending it, but having two problems:
I hard coded the info sent to the API (year and term) since it is supposed to return the information I'm attempting to store, and it doesn't work
I'm trying to use it as a function, to then populate the table, but it keeps giving me an error due to it not being able to get the info in the first place, so I'm guessing the problem is with the way I'm requesting info from the API (I'm new to the whole React/JavaScript thing)
this is sort of what my code looks like
class Stu extends Component {
constructor(props) {
super(props);
this.state = {
students: [],
}
this.fetch = this.fetch.bind(this)
this.getStudents = this.getStudents.bind(this)
}
getStudents(year, term) {
return this.fetch(`http://10.123.456.321/Stu/`, {
method: 'POST',
body: JSON.stringify({
year,
term
})
}).then(data => {
this.setState({
students: data.results.map(item => ({
firstName: item.firstName,
lastName: item.lastName,
ID: item.ID,
term: item.term,
year: item.year,
}))
})
console.log(this.state);
})
}
fetch(url, options) {
// performs api calls sending the required authentication headers
const headers = {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
return fetch(url, {
headers,
...options
})
.then(response => response.json())
}
renderTableData() {
return this.state.projects.map((student, index) => {
const { firstName, lastName, ID, term, year } = student
return (
<tr>
<td>{firstName}</td>
<td>{lastName}</td>
<td>{ID}</td>
<td>{term}</td>
<td>{year}</td>
</tr>
)
})
}
//
render() {
return (
<Container>
{this.getStudents("2019", "summer")} // this is supposed to be called from a button click, but I tried hardcoding those values and it doesn't call the API properly, both values are strings
<Form>
<div>
<table id='students'>
<tbody>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>ID</th>
<th>Term</th>
<th>Year</th>
</tr>
{this.renderTableData()}
</tbody>
</table>
</div>
</Form>
</Container>
);
}
}
export default Stu;