I'm new in react and I have a problem. When I choose an option in select, I want to display this option's data with innerHTML. When I do console.log(data) I get data from my request. But, on my page I get [object Promise] or [object Object] and not the data. I'm on it since a few weeks and I can't do it, please help me !
PS: sorry for my english, I'm French :).
Here, my code in jsx :
import React from 'react';
import {Link} from "react-router-dom";
import axios from "axios";
import Select from "../../components/forms/Select";
class Persons extends React.Component {
constructor(props) {
super(props);
this.state = {
render: false,
error: null,
isLoaded: false,
persons: [],
person: [],
id: ''
};
//this.handleChange = this.handleChange.bind(this);
}
fetchPersons() {
return axios .get("'http://localhost:8000/api/persons")
//.then(res => res)
.then((result) => {
console.log("result: ",result);
this.setState({
isLoaded: true,
persons: result.data["hydra:member"]
})
}),
(error) => {
this.setState({
isLoaded: true,
error
})
console.log(error);
}
}
async fetchPerson(id) {
console.log(id);
try {
return await fetch("'http://localhost:8000/api/persons/" + id)
.then(res => res.json())
.then((result) => {
console.log("rr " + result); //object Object
this.setState({
isLoaded: true,
person: result.data
})
console.log("result1: ",result);
return result;
})
}catch(error) {
this.setState({
error
})
console.log("Erreur: ", error);
}
}
componentDidMount() {
this.fetchPersons();
}
handleChange = (event) => {
const show = document.getElementById("show");
console.log("I'm in handleChange");
const value = event.target.value;
let select = this.fetchPerson(value);
console.log("Select: " + select);
console.log("Select2: " , [select]);
console.log("Select: " + [{select}]);
console.log("Select2: " , [{select}]);
let newContent = "You selected " + JSON.stringify([{select}]);
show.innerHTML = newContent;
}
render() {
const {error, isLoaded, persons, person} = this.state;
if (error) {
return <div>Erreur : {error.message}</div>;
} else if (!isLoaded) {
return <div>Chargement…</div>;
} else {
return (
<div id="show">
<h1>Test</h1>
<Select id="selectPerson" name="persons" label="Persons" value={persons.id} onChange={this.handleChange.bind(this)}>
<option key={0} value={null}>Choice</option>
{this.state.persons && this.state.persons.map(person => (
<option key={person.id} value={person.id}>{person.ref} </option>
))}
</Select>
{this.state.persons && this.state.persons.map(person =>
<tr key={person.id}>
<td>{person.lname}</td>
<td>{person.fname}</td>
<td>{person.sexe}</td>
<td>{person.age}</td>
</tr>)}
</div>
)
}
}
};
export default Persons;