Так что новшество в React здесь, и я хочу сделать простое поле поиска, где пользователь отправляет «вопрос», а JSON возвращает значения «результатов».
Запрос проходит, и я получаю ответ, единственное, что я не могу найти, - это взять результаты и отобразить их на внешнем интерфейсе.
class Search extends Component {
state = {
searchValue: "",
searchSection: "",
results: [],
// section: []
};
handleOnChange = event => {
this.setState({ searchValue: event.target.value });
};
handleSearch = () => {
this.makeApiCall(this.state.searchValue);
};
makeApiCall() {
fetch("http://example.com/json", {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
question: (this.state.searchValue),
section: (this.state.searchSection),
})
})
.then((response) => response.json())
.then((responseData) => {
console.log(
"POST Response",
"Response Body -> " + JSON.stringify(responseData)
)
return responseData
})
.then(results => this.setState({results: results.value}))
};
render() {
return (
<div id="main" className="py-16">
<label className="block uppercase tracking-wide text-gray-700 text-xs font-bold mb-2" for="grid-first-name">
Ask a question
</label>
<input
name="text"
type="text"
placeholder=""
onChange={event => this.handleOnChange(event)}
value={this.state.searchValue}
className="shadow-sm appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline"
/>
<button onClick={this.handleSearch} className="cursor-pointer mt-5 bg-white hover:bg-gray-100 text-gray-800 font-semibold py-2 px-4 border border-gray-400 rounded-full shadow">Search</button>
// DISPLAYING THEM ON THE FRONT HERE
{this.state.results ? (
<div id="question-container">
{this.state.results.map((result) => (
<div className="result">
<h2>{result.title}</h2>
<p>{result.sentences}</p>
</div>
))}
</div>
) : (
<p>Can't find results for your question</p>
)}
</div>
);
}
}
export default Search;
Мой JSON это как:
{
"request": {
"date_from": "",
"date_to": "",
"question": "User question here",
"section": null
},
"results": {
"docs": [
{
"title": " "
"section": " "
}
]
}
}
И мне нужно отобразить несколько вопросов из JSON