Madiever
Madiever

Reputation: 25

how do I get the result of a function in another component?

I have a function

export const getFieldId = (ownerProps: any) => {
  const selectedPath = ownerProps.ctx.path;
  console.warn(selectedPath[selectedPath.length - 1]);
  return selectedPath[selectedPath.length - 1];
};

I need to get its result in another component. How do I do this?

Upvotes: 0

Views: 40

Answers (1)

yesIamFaded
yesIamFaded

Reputation: 2068

I guess you can either pass it as a Navigation Param if you are navigating to the Screen from the Screen where this function is executed.

Or use Redux / the Redux Store to set the state globally and get the value in the component where you need it.

You can also use AsyncStorage to save the value and get the value in the component.

For an easy AsyncStorage usage:

You can store and get Data with this functions:

  const storeData = async (key, value) => {
    try {
      await AsyncStorage.setItem(key, value); 
    } catch (error) {
      console.log(error);
    }
  };

  const getData = async key => {
    try {
      const data = await AsyncStorage.getItem(key);
      if (data !== null) {
        console.log(data);
        return data;
      }
    } catch (error) {
      console.log(error);
    }
  };

Then you can call the functions and get the values like this:

Store the value:

storeData("Keyname", the value);

Get the value and set it as state for example:

  await getData"Keyname") 
    .then((data) => data)
    .then((value) => this.setState({ stateVariable: value }))
    .catch((err) => console.log("AsyncStorageErr: " + err));

Upvotes: 1

Related Questions