'I cant get my searching program to work on react
I am new to react and I am currently working on this simple program that searches from github api and returns a list of repositorys names and urls. I cant get it to work. The earlier version worked and i could fetch up to five different names and urls. Here is my code:
import React, { useState } from 'react';
import './App.css';
function App() {
const [items, setItems] = useState('[]');
const [keyword, setKeyword] = useState('')
const fetchData = () => {
fetch('https://api.github.com/search/repositories?q=' + keyword)
.then(response => {
if (response.status !== 200) {
throw new Error('Response status not ok');
}
return response.json();
})
.then(resData => {
setItems(resData.data);
})
};
const inputChanged = (event) => {
setKeyword(event.target.value);
}
return (
<div className="App">
<h4>Repositories</h4>
<input placeholder="Keyword" value={keyword} onChange={inputChanged} />
<button onClick={fetchData}>Search</button>
<h4>Name</h4>
<ul>{items.full_name} {items.url}</ul>
</div>
);
}
export default App;
The searchbar works fine but after that it doesnt do anything.
Solution 1:[1]
I think you might've made a mistake in your naming setItems(resData.data);.
Looks like it should be setItems(resData.items); instead.
You also need to map through your data once it's been fetched.
<ul>
{items.map((item) => (
<li>
{item.full_name} {item.url}
</li>
))}
</ul>
You also have set your initial item value as "[]", which should be []. "[]" is a string and cannot be iterated over.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | bopbopbop |
