useState and useEffect not playing nice with an API call

  const [inputText, setInputText] = useState('');
  const [searchTerm, setSearchTerm] = useState('');
  const [data, setData] = useState(null);

  const handleChange = (event) => {
    setInputText(event.target.value);
  };

  const handleSubmit = (event) => {
    event.preventDefault();
    setSearchTerm(inputText)
    console.log(inputText)
    setInputText('')
  };

  useEffect(() => {
    if (searchTerm) {
      console.log('starting fetch with -> ', `https://imdb-api.com/en/API/SearchTitle/k_ix11kdvq/${searchTerm}`)
      fetch(`https://imdb-api.com/en/API/SearchTitle/k_ix11kdvq/${searchTerm}`)
      .then(res => {
          res.json()
          console.log('json data')
        })
      .then(json => {
          setData(json)
          console.log('setting data to this value', json)
        })
      .then(console.log('current data value after setData runs -> ', data))
    }
  }, [searchTerm])

Wanted to redo a simple HTML webpage I build in my bootcamp within React.
As you can see I have some super professional console logs in here to track just wth is going on with this data.

inception
App.js:36 starting fetch with ->  https://imdb-api.com/en/API/SearchTitle/k_ix11kdvq/inception
App.js:45 current data value after setData runs ->  null
App.js:40 json data
App.js:44 setting data to this value undefined
index.js:6 data value within body component currently is undefined
installHook.js:1861 data value within body component currently is undefined
index.js:6 data value within body component currently is undefined
installHook.js:1861 data value within body component currently is undefined
App.js:36 starting fetch with ->  https://imdb-api.com/en/API/SearchTitle/k_ix11kdvq/inception
App.js:45 current data value after setData runs ->  undefined
App.js:40 json data
App.js:44 setting data to this value undefined

Yeeeeeaaah….

It’s not working asynchronously at all. Obviously I’m being stupid, but I just can’t figure out where.

I’m trying to utilize useEffect to make an API call, wait for the data, then jsonify it, and setData to that value so that I can display it.

I tried using axios and doing an async/await function, no dice.

Please help 😊

>Solution :

You’re not returning your res.json(). Since you’re not returning anything, the next .then is empty.

 useEffect(() => {
    if (searchTerm) {
      console.log('starting fetch with -> ', `https://imdb-api.com/en/API/SearchTitle/k_ix11kdvq/${searchTerm}`)
      fetch(`https://imdb-api.com/en/API/SearchTitle/k_ix11kdvq/${searchTerm}`)
      .then(res => {
          console.log('json data')
          return res.json()
        })
      .then(json => {
          setData(json)
          console.log('setting data to this value', json)
        })
      .then(console.log('current data value after setData runs -> ', data))
    }
  }, [searchTerm])

Leave a Reply