I'm trying to set my state to data fetched from an API. However when I console.log the state (items
in this instance), it returns an empty array.
This is my code:
const Search = () => {
const apiKey = 'xxxxxxx';
const [input, setInput] = useState('');
const [items, setItems] = useState([]);
const handleSubmit = (e) => {
searchAPI();
};
const searchAPI = async () => {
const res = await fetch(`http://www.omdbapi.com/?apikey=${apiKey}&s=${input}`);
const data = await res.json();
setItems([data.Search]);
console.log(items)
};
return (
<form>
<input onChange={(e) => setInput(e.target.value)}></input>
<Link to={{ pathname: '/results', state: items }}>
<button type="submit" onClick={handleSubmit}>
search
</button>
</Link>
</form>
);
};