0

I want to show data from Django Rest Framework into DropDownPicker React-Native (https://github.com/hossein-zare/react-native-dropdown-picker) this is my code:

import React, { useState, useEffect } from "react";
import { StyleSheet, View, Text, Image, FlatList, Button, TouchableOpacity } from "react-native";
import client from "./../../api/client";
import DropDownPicker from 'react-native-dropdown-picker';


const Droplo = ({navigation, route}) => {
  const [detailha, setDetailha] = useState("");
  const [value, setValue] = useState(null);
  let controller;

  const getDetailha = async (url) => {
    try {
      const response = await client.get(url);
      if (!response.ok) {
        setDetailha(response.data);
        console.log(response.data)
      }
    } catch (error) {
      console.log(error);
    }
  };
  useEffect(()=>{ getDetailha('/habilidad/'); }, [])

  return (
      <View>
        <DropDownPicker
            items={detailha}
            controller={instance => controller = instance}
            onChangeList={(items, callback) => {
                new Promise((resolve, reject) => resolve(setDetailha(items)))
                    .then(() => callback())
                    .catch(() => {});
            }}
            defaultValue={value}
            onChangeItem={item => setValue(item.nombre_habilidad)}
        />
      </View>
    );
  }

export default Droplo;

The data is:

enter image description here

and the error is:

enter image description here

Thank You!

1 Answers1

0

Your data is not properly formatted.

See this paragraph: https://github.com/hossein-zare/react-native-dropdown-picker#single-item

The props item should be formatted like this :

[
  { label: 'item-label', value: 'item-value', icon: () => <span>your-icon</span> }, 
  ... 
]

So you can change the server's response or make an new array from the response data and pass item prop.

responseData.map(elem => ({label: elem.nombre_habilidad, value: elem.nombre_habilidad})

Also you should chagne initial value of state detailha, because item prop needs array type. (Before the API is fetched, react-native-dropdown-picker component will render with the intial value) You can initialize with empty array:

const [detailha, setDetailha] = useState([]);

This change will fix the error you provided

cereme
  • 280
  • 1
  • 18