Search code examples
reactjses6-promise

How to loop through results from a Promise to pass it to React components


I am thinking this is because I need to learn more about Async and Promises in JS But so I have some Async API that returns some people's info, something like this in the structure of it shows in Chrome's Console. I copied the first guy:

Promise {<fulfilled>: Array(12)}
__proto__: Promise
[[PromiseState]]: "fulfilled"
[[PromiseResult]]: Array(12)
0:
id: "ec6eee79-5ab8-44a9-8fbf-35668ec3a668"
name: "John Travolta"
__proto__: Object

So I wrote a simple component to loop through them for now, but clearly it is not the right way. I had to comment out the part that is failing. but that's the kind of thing I am hoping to accomplish. So how should I change this?

const UserComponent = (props) => {
  const results = API.getSomePeopleInfo().then((response) => {
    const result = Promise.resolve(response.data);
    console.log("so data was this: ", result);
  });

  return (
    <div>
      <h1>A user</h1>
      {/*{results.map((r) => (*/}
      {/*  <li>{r.name}</li>*/}
      {/*))}*/}
    </div>
  );
};

Solution

  • You are using a async function, that doesn't resolve instantly, it means that when you reach the render method, result's won't have data. You could just make it a state variable and update it in the then callback:

    import { useState } from 'react'
    
    const UserComponent = (props) => {
      // Using react with hooks
      const [results, setResults] = useState([]);
    
      API.getSomePeopleInfo().then((response) => {
        const peoples = response.data;
        setResults(peoples)
      });
    
      return (
        <div>
          <h1>A user</h1>
          {/*{results && results.map((r) => (*/}
          {/*  <li>{r.name}</li>*/}
          {/*))}*/}
        </div>
      );
    };