Mr. Engineer
Mr. Engineer

Reputation: 375

React: getting TypeError when trying to return JSON response from fetch API call

I have Node server and REST API, which returns contact info in JSON format, and now I'm trying to display that information to user when user clicks certain menu button. My server works just fine but when trying to display the data I'm getting error message:

TypeError: Cannot read property 'state' of undefined

Here is my React code:

import './App.css';
import MenuItems from './components/Navbar/MenuItems';
import ReactDOM from 'react-dom'
import React, { useState } from 'react'

function App() {

  const [selectedItem, setSelectedItem, contacts] = useState();
  getContactInfo();
  return (
    <div className="App">
      <div className="content">
        <h1>My website</h1>
        {MenuItems.MenuItems.map((item, index) => (
          <li key={index} onClick={() => setSelectedItem(item.title)}
          style={{cursor: "pointer"}}>{item.title}</li>
        ))}
        {selectedItem && (
          <h1 style={{textAlign: 'center'}}>{selectedItem}</h1>
        )}
        {selectedItem == 'Contact_us' &&
        <div>
          {this.state.contacts.map(contacts => 
          <div key={contacts.name}> {contacts.phone} </div>)}
        </div>
        }

      </div>
    </div>
    
  );
}
function getContactInfo() {
    fetch('http://127.0.0.1:5000/listUsers')
    .then(res => res.json())
    .then(contacts => this.setState({contacts}))
    .catch(console.log)
}

export default App;

Basically I'm trying fetch the information from server before user clicks menu button and display it after menu button has been clicked. I'm doing this to avoid "undefined" exceptions but it doesn't seem to help. Any advise is highly appreciated.

Upvotes: 0

Views: 94

Answers (1)

Joseph Fletcher
Joseph Fletcher

Reputation: 176

UseState has the syntax:

const [state, setState] = useState(initialState);

(https://reactjs.org/docs/hooks-state.html)

You need a seperate state for your contacts:

const [contacts, setContacts] = useState({})

Then use setContact in your getContactInfo() function to set the contacts state:

function getContactInfo() {
    fetch('http://127.0.0.1:5000/listUsers')
    .then(res => res.json())
    .then(contacts => setContacts(contacts))
    .catch(console.log)
}

Also, the getContactInfo() function needs to be inside your App, it's currently out of scope.

Upvotes: 1

Related Questions