Skip to content
Advertisement

How to solve Cannot read property ‘map’ of undefined error in React js?

I am building a react js application with dummy backend using json-server.I am implementing a dropdown list but I am getting Cannot read property 'map' of undefined error on fetching from api.The api is working fine in browser but while fetching in react it is giving me this error.

My component:

import React from 'react';

var values;

class ApiDropDown extends React.Component {

    constructor(){
        super();
        this.state = {
            options: []
        }  
    }

   componentDidMount(){
       this.fetchOptions()
    }

    fetchOptions(){
        fetch('http://localhost:5000/groups')
            .then((res) => {
                
                return res.json();
            }).then((json) => {
                values = json;
                this.setState({options: values.groups})
                console.log(values);
            });
    }
    render(){
    
        return <div>
            <select>
                { this.state.options.map((option, key) => <option key={key} >{option}</option>) }
            </select>
            </div>;
    



}
}

export default ApiDropDown;

My db.json for dummy backend:

{  
  "groups":[  
     {  
        "key":"version",
        "apis":"system_info"
     },
     {  
        "key":"admin",
        "name":"patients"
     },
     {  
        "id":"admin2",
        "name":"doctors"
     }
     
  ]
}

Here’s how I am rendering my ApiDropDown component:

 return (
    <form className="add-form" onSubmit={onSubmit}>
      <div>
      <ApiDropDown/> //ApiDropDown Component
      </div>
      <div >
        <input className="clientparams"
          type="text"
          placeholder="Add Client"
          value={client_name}
          onChange={(e) => setText(e.target.value)}
        />
      </div>
      </form>

Can someone help me with this error?

Advertisement

Answer

Two things that should be correct.

  1. { this.state.options.map((option, key) => <option key={key} >{option}</option>) } In this you are trying to bind the object as react child, so instead of this it should be {{ this.state.options.map((option, key) => <option key={key} >{option["apis"]}</option>) }
  2. You no need to declare a variable to store the fetch values you can directly set it to state like this. this.setState({options: json.groups})

Here is the working example of your code(fetch call is different): https://codesandbox.io/embed/nifty-lamport-mzmro?fontsize=14&hidenavigation=1&theme=dark

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement