Guilherme Moretto
Guilherme Moretto

Reputation: 103

How can I pass a param for a function inside my React Native Function Component?

I have a Picker component that is populated with data from a local realm database, the component has a function that receives the name of the database schema as a param. What I want to do is, instead of writing the name of the schema inside the function, to receive it as a prop or a param, so I can use the same component to show pickers with different information.

This is my code:

const PickerDB: React.FC<PickerProps> = (props) => {
    const [data, setData] = useState([]);

    async function loadData() {
        setData(await GetDataFromDB('source')); // this is what I want to modify
    }

    useEffect(() => {
        loadData();
    }, [])

    let values = data.map((data) => {
        return (
            <Picker.Item
                label={data.description}
                value={data.id}
                key={data.id}
            />
        )
    })

    return (
        <Picker
            selectedValue={props.selectedValue}
            style={{ height: 45, width: "70%" }}
            onValueChange={props.onValueChange}
        >
            {values}
        </Picker>
    );

I need to create my component using React.FC<PickerProps> because of other functions inside my app.

I would like to use my component like this:

<PickerDB source={'schemaName'} />

Upvotes: 1

Views: 282

Answers (1)

Taghi Khavari
Taghi Khavari

Reputation: 6582

Here is what you need to do:

async function loadData(source) {
  setData(await GetDataFromDB(source)); // this is what I want to modify
}

useEffect(() => {
  if (props.source) {
    loadData(props.source);
  }
}, [props.source]);

Upvotes: 2

Related Questions