Search code examples
reactjses6-promisereact-map-gl

How can I import the const data from another file using Promise (React)


I am trying to import data from another file into my React component. The data is acquired via an asynchronous function resolving to the data.

However I am getting an error when trying to map over the test data in the consuming component. I think this is something to do with the fact that my getter returns a promise.

The component renders fine if I just inline the data as a const in the same file.

JS file (export)

 export const test = () => {
        return new Promise((resolve, reject) => {
            resolve(data());
        });
     
    };
    
    const data = () => {
        return [
            {
                name: "tom",
                car: "tesla"
            },
            {
                name: "sam",
                car: "honda"
            },
            {
                name: "may",
                car: ["toyota", "BMW"],
            },
            
        ];
    };

Jsx file (import)

import { test } from "./test"

function List() {

  return (
    <div className="food">
      
      {test.map((value,index) => (
         <div key={index}>
           <p>{value.name}</p>
           <p>{value.car}</p>
           </div>    
         ))}
    </div>   
  ) 
}
export default List

Solution

  • Test isn't an array variable, it's a function that returns a Promise object.

    To fix your problem follow these steps:

    1. Declare state data and initial its value to [].

    2. AdduseEffect hook to fetch your data.

    3. Use state data to render your html.

      import React, { useState, useEffect } from 'react';
      import { test } from './test';
      
      function List() {
        const [data, setData] = useState([]);
      
        useEffect(() => {
          test().then((res) => setData(res));
        }, []);
      
        return (
          <div className="food">
            {data.map((value, index) => (
              <div key={index}>
                <p>{value.name}</p>
                <p>{value.car}</p>
              </div>
            ))}
          </div>
        );
      }
      export default List;
      

    This is a simple demo: https://stackblitz.com/edit/react-2pmxgb?file=src%2FApp.js