0

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>
  );
};
charlieyin
  • 371
  • 6
  • 16
  • Does this answer your question? [useState set method not reflecting change immediately](https://stackoverflow.com/questions/54069253/usestate-set-method-not-reflecting-change-immediately) – Emile Bergeron Jul 08 '20 at 01:22

2 Answers2

2

Because setState is asynchronous

setState() does not always immediately update the component. It may batch or defer the update until later. This makes reading this.state right after calling setState() a potential pitfall

https://reactjs.org/docs/react-component.html#setstate

ludwiguer
  • 2,177
  • 2
  • 15
  • 21
0

setState() takes a callback function as a second argument which will ensure that the state is updated. For hooks, you need to do

useEffect(() => {
  console.log(items)
}, [items]);
Anne
  • 159
  • 7