Reputation: 99
I am makeing my first steps in react. Now I want to fetch some data from thedogapi.com and and to show the results as cards below the search input.
But it is not working and I am not sure why:
let data = [];
function ApiSearch() {
async function changeHandler(e) {
//console.log('https://api.thedogapi.com/v1/breeds/search?q=' + e.target.value.toString());
let response =
await fetch('https://api.thedogapi.com/v1/breeds/search?q=' + e.target.value.toString(), {
mode: 'cors',
headers: {
'x-api-key': 'XXXXXXXXXXXXXXXXXXXX'
},
})
data = await response.text();
data = JSON.parse(data);
ApiResults();
}
return (
<Form onSubmit={(e) => e.preventDefault()}>
<Form.Group className="mb-3" controlId="fromAPISearch">
<Form.Label>Search for a Breed</Form.Label>
<Form.Control
type="text"
placeholder="Some breed.."
onChange={changeHandler}
/>
</Form.Group>
<Button variant="primary" type="submit">
Save
</Button>
<Button variant="danger" type="reset">
Reset
</Button>
<Button variant="warning" type="reset">
Delete All Entries
</Button>
</Form>
);
}
ApiResults() can show me the data due console.log() but it is not rendering anything here.
function ApiResults() {
const results = [];
data.forEach(d => {
results.push(
<Card key={d.id}>
<Card.Body>
{d.name}
</Card.Body>
</Card>
)
})
return (
<Col>
{
results.map(
result => {return result}
)
}
</Col>
)
}
I Call 2 Components, should be the one that shows the results that gathers.
function App() {
return (
<Container>
<Row>
<Col>
<br/>
<ApiSearch/>
</Col>
</Row>
<Row>
<ApiResults/>
</Row>
</Container>
);
}
export default App;
Upvotes: 0
Views: 71
Reputation: 195
In order for your component to re-render when a variable changes that variables need to be a state. You can use useState hook to create a state and every time you change that with the setter your component should rer-ender and show its real-time content
Upvotes: 2