Sindhuja
Sindhuja

Reputation: 1

fetching json data from local file

TypeError: this.state.data.map is not a function Trying to access local json data. import React, { Component } from 'react'; import './index.css'

   class App extends Component {
     constructor(){
        super() 
        this.state = {
         data: []
         }

       }
     componentDidMount()
      {
        fetch("./employeeData.json")
       .then(res => res.json()) 
       .then(daabta => {
        this.setState({data: daabta })
        } )
       }
     render() {
       return (
         <table>
          <tbody>{this.state.data.map((item, index) => 
            <tr key = {index}>
              <td>{item.userId}</td>
              <td>{item.firstName}</td>
              <td>{item.lastName}</td>
              <td>{item.region}</td>
             </tr>
            )      
           })}</tbody>
         </table>
        )
       }
      }
     export default App;

Upvotes: 0

Views: 51

Answers (1)

octobus
octobus

Reputation: 1276

You can just import your json file directly at the top of your component like

import * as employeeData from "./employeeData.json";

but be careful your json data would be inside and object named default so when you want to access the data you should use employeeData.default

Upvotes: 2

Related Questions