I have problem with fetching data in JSX react component

Viewed 116

I want to get data from swapi and do jsx component with this data, but react give me a error when i want to use this data This my fetch

var promise = await fetch('https://swapi.dev/api/people/1/')
  .then((res) =>  res.json() )
  .then(data => setLuke(data.data)) 

And this is react error:

Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead. i dont know what to do can you help me with this little problem

1 Answers

You are probably rendering your promise var instead of {luke}. Also note that data will be a json object so you won't be able to render it directly. You will need to stringify it first. data.data which you are currently using will also be undefined. Just use data, it already contains the json.

await fetch("https://swapi.dev/api/people/1/")
      .then(res => res.json())
      .then(data => {
        setLuke(JSON.stringify(data));
      });

You should then be able to render it using {luke}

Related