Search code examples
javascriptreactjsreact-nativepicker

React native Picker item list binding with fetch request and selecting an item


Need to bind a list of sports taken from a fetch request in useEffect() to react-native Picker and select a sport from the picker.item to a variable. Found a Solution using a class-based component. Would need a solution in a functional component with network binding and item selection

import React, { useState, useEffect } from 'react'
import { Picker } from '@react-native-picker/picker';

// Functional Component
export default function PlayerRegistration() {

// Picker.item List
const [listofsports, setListOfSports] = useState([])
// Selected Item variable
const [selectedItem, setSelectedSport] = useState()

// Fetch Function
 const getListOfPlayersList = () => {
        const api = API();
        console.log('working backendapi', api)
        const sportscentersapi = `${api}/sports`;

        const test = fetch(sportscentersapi, {
            method: 'GET',
            headers: {
                Accept: 'application/json',
                'Content-Type': 'application/json',
            }
        })
            .then(response => response.json())
            .then(data => {
                //console.log(data),
                setListOfSports({ listofsports: data })
            });
    }

// ComponentDidmount or ComponentDidUpdate Equivalent
useEffect(() => {
        getListOfPlayersList();
// Returning list looks similar to this.
//[{ "idsport": 1, "sportname": "Badminton" }, { "idsport": 2,"sportname": "Golf"}]

});

// JSX
    return ( <Picker
                selectedValue={selectedItem}
                onValueChange={(itemValue, itemIndex) =>
                    setSelectedSport(itemValue)
                }>
                {

                listofsports.map((item, index) => {
                    return (<Picker.Item
                        key={index}
                        label={`${item.sportname.toString()}`}
                        value={`${item.sportname}`} />)
                })

                }
            </Picker>)

}


Solution

  • Refering to this question I got an answer which is working as expected.

    import React, { useState, useEffect } from "react";
    import { Picker } from "@react-native-picker/picker";
    
    // Functional Component
    export default function PlayerRegistration() {
      // Picker.item List
      const [listofSports, setlistofSports] = useState([]);
      // Selected Item variable
      const [selectedValue, setSelectedValue] = useState("");
    
      // Fetch Function
      const getListOfPlayersList = async () => {
        const api = 'http://localhost:3000';
        console.log("working backendapi", api);
        const sportscentersapi = `${api}/sports`;
    
        const test = fetch(sportscentersapi, {
           method: "GET",
           headers: {
             'Accept': 'application/json',
             'Content-Type': 'application/json'
           }
        })
           .then((response) => response.json())
           .then((json) => setlistofSports(json.data))
           .catch((error) => console.error(error));
        // Incase if you need static json could use this
        // return [
        //   { idsport: 1, sportname: "Badminton" },
        //   { idsport: 2, sportname: "Golf" }
        // ];
      };
    
      // ComponentDidmount or ComponentDidUpdate Equivalent
      useEffect(() => {
        getListOfPlayersList();
      }, []);
    
    
      const renderSportsList = () => {
        return listofSports.map((sport, index) => {
          return <Picker.item key={index} label={sport.idsport} 
          value={sport.sportname} />;
        });
      };
    
      // JSX
      return (
         <Picker
           selectedValue={selectedValue}
           style={{ height: 40, width: 150 }}
           onValueChange={(itemValue, itemIndex) => {
             setSelectedValue(itemValue);
           }}
         >
           {renderSportsList()}
         </Picker>
      );
    }