I am getting a "Objects are not valid as a React child" error, when I am calling hooks callback function " setSearchResults " to set state. The state value is an array having objects but I am not sure why I am getting this error and how to resolve it.
function WikiSearch() {
const [searchKeyword, setSearchKeyword] = useState('');
const [searchResults, setSearchResults] = useState([]);
function onSearchChangeHandle(event = "") {
let term = event.target.value;
setSearchKeyword(term);
getSearchResult(term);
}
async function getSearchResult(term) {
const url = 'https://en.wikipedia.org/w/api.php';
try {
const {data} = await axios.get(url, {
params: {
action: 'query',
origin: '*',
format: 'json',
list: 'search',
srsearch: term
}
});
// search is an array having objects
setSearchResults(data.query.search); // => causing error
} catch (error) {
console.error(error);
}
}
const listData = searchResults.map((search ) => {
return (
<Fragment key={search.pageid}>
<div>
<span>
{search.title}
</span>
</div>
<div>
<span>
{search.snippet}
</span>
</div>
</Fragment>
)
});
return (
<div>
<div className="ui form">
<div className="field">
<label>Search</label>
<input className="input" type="text" name="search" value={searchKeyword} onChange={(e) => onSearchChangeHandle(e) }/>
</div>
</div>
{listData}
</div>
)
}
I want to loop over those search results and show data in the list. Probably search.title and search.snippet .
use JSON.stringify(*your object*)
to turn your array/object into a string, because JS objects cannot be a valid React Child-elements
...
return (
<div>
<div className="ui form">
<div className="field">
<label>Search</label>
<input className="input" type="text" name="search" value={searchKeyword} onChange={(e) => onSearchChangeHandle(e) }/>
</div>
{JSON.stringify(searchResults)}
</div>
</div>
)
...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.