0

I've been reading through Stack Overflow on this and struggling to solve my issue. I am still very junior, so I may have read the correct fix and been to dense to understand it.

The intention is set a piece of React state to the returned object from an API query.

That being said, here's the code. EDIT: fixed the props

export const Background = ({background, setBackground}) => {
  //goal is to query a random land and set the background to the full art of that land on page load
  const backgroundQuery = async () => { 
    const query = "https://api.scryfall.com/cards/random?q=%28type%3Aland%29+is%3Aartcrop"
    const response = await fetch(query);
    console.log(response)
    const data = await response.json();
    console.log(data);
    setBackground(data);
  }

  return(
    <div>
      {background.length && <image src={background.image_uris.art_crop} alt="background image, basic full art mtg land"></image>}
      <button onClick={backgroundQuery}> Get Image </button>
    </div>
  )
};

The console.log(data) yields the result I'd like, but I know I am incorrectly resolving this promise. The error yielded is below:

Uncaught (in promise) TypeError: setBackground is not a function
    at backgroundQuery (Background.js:9:1)
dconnenc
  • 31
  • 6
  • 1
    First off you're not destructuring your props `({background, setBackground})` assuming you're receiving those from a parent. Second it looks like you should be calling `backgroundQuery` in a `useEffect`. see: [How to call an async function inside a UseEffect() in React?](https://stackoverflow.com/questions/56838392/how-to-call-an-async-function-inside-a-useeffect-in-react) – pilchard Jun 28 '22 at 18:10
  • How is `Background` being called? – Heretic Monkey Jun 28 '22 at 18:11
  • @pilchard It's called from the button click handler, no need for an effect – Bergi Jun 28 '22 at 18:24
  • doh! forgot about the destructing, thing that will help me make headway, and I'll review the linked useEffect link – dconnenc Jun 28 '22 at 18:41

0 Answers0