2

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

4
  • show your render.. Probably you are just rendering promisee ?
    – Panther
    May 8, 2020 at 14:57
  • const Main = async() => { const [luke, setLuke] = useState() var req = async () => { var promise = await fetch('swapi.dev/api/people/1/').then((res) => res.json() ).then(data => setLuke(data.data)) console.log(luke) } useEffect(() => req()) return (<> {luke} </>) }
    – dude
    May 8, 2020 at 15:01
  • Your data.data from the response is probably an object. May 8, 2020 at 15:08
  • You Main is async. And hope you are rendering main.. so it is a promise. You should remove the async in Main and try it
    – Panther
    May 8, 2020 at 16:00

1 Answer 1

1

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}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.