Mr. Hankey
Mr. Hankey

Reputation: 1244

Dropdown from JSON response in React with hooks

I want to make a dropdown from data I get from a REST API. Unfortunately, what I have already tried doesn't work, nothing is shown in the dropdown. See code for reference. It says '

×
TypeError: teams.current.map is not a function

'

My object looks like

[
    {
        "id": 5,
        "name": "hasda"
    },
    {
        "id": 6,
        "name": "asdasd"
    }
]

I took a look at that link, but it didn't help much. I hope you can help me

    import React, { useState, useEffect, useRef } from "react";
    import { useHistory } from "react-router-dom";
    import axios from 'axios'
    
    
    function Navbar() {
        const [team, setTeam] = useState([]);
    
    
        useEffect(() => {
            getTeams()
        }, []);
    
        const getTeams = () => {
            axios
                .get(`${process.env.REACT_APP_API_URL}/team/all`, {})
                .then((res) => {
                    console.log(res.data);
                    setTeam(res.data)
                })
                .catch((error) => {
                    console.log(error)
                })
        }
    
    
        return (
    
                 <p className="navbar-item">Mannschaften</p>
    
                 <div className="navbar-dropdown">
    
                 {/* {team.current.map((d, i) => (
    
                      <a className="navbar-item" href={i.mannschaftsname}>{i.mannschaftsname}</a>
    
                  ))}  */}



                 {/* {
                   this.state.team.map((obj) => {
                   return <option team={obj.id}>{obj.name}</option>
                    })
                 } */}

                   <a className="navbar-item" href="/login">Test</a>
                   </div>
            </div>

    );
}

export default Navbar;

Upvotes: 0

Views: 522

Answers (1)

Mohit kumar
Mohit kumar

Reputation: 487

Your state name is team and not teams. So, you can try something like:

<select>
{

     team?.map((obj) => {
          return <option team={obj.id}>{obj.name}</option>
     })  
}
</select>

Upvotes: 1

Related Questions