2
votes

My problem is that I can't able to pass the function as a param to the header component in react-navigation v5.

From the given code below in filtersscreen.js, I want to pass savefilters to headerRight which is in navigation.js.

I can view the save param in log-1. But Why can't I able to get the save param in log-2 which is FilterNavigator.

I'm receiving warning when I use setParams() - "Non-serializable values were found in the navigation state, which can break usage such as persisting and restoring state. This might happen if you passed non-serializable values such as function, class instances etc. in params. If you need to use components with callbacks in your options, you can use 'navigation.setOptions' instead. See https://reactnavigation.org/docs/troubleshooting.html#i-get-the-warning-we-found-non-serializable-values-in-the-navigation-state for more details."

When I use navigation.setOptions({ save: savefilters }) I can't find the save in route.params.save

I new to react-native, I request you to help me out of this problem.

I read the docs React Navigation v5.

I logged the output below. Thank You.

navigation.js

const FiltersNavigator = props => {
  return (
    <screen.Navigator initialRouteName="Filters">
      <screen.Screen
        options={{
          title: 'Filters',
          headerRight: () => (
            <View>
              <TouchableNativeFeedback>
                <MaterialCommunityIcons
                  name="content-save"
                  color="white"
                  size={28}
                  style={{padding: 15}}
                  onPress={() => console.log(props)} //log-2 attached below
                />
              </TouchableNativeFeedback>
            </View>
          ),
        }}
        name="Filters Meals"
        component={FiltersScreen}
      />
    </screen.Navigator>
  );
};

FiltersScreen.js

const FilterSwitch = props => {
  return (
    <View style={styles.filterContainer}>
      <Text>{props.label}</Text>
      <Switch
        trackColor={{true: Colors.primaryColor}}
        thumbColor={Colors.primaryColor}
        value={props.state}
        onValueChange={props.onChange}
      />
    </View>
  );
};

const FiltersScreen = props => {
  const {navigation} = props;
  const [isGlutenFree, setIsGlutenFree] = useState(false);
  const [isLactoseFree, setIsLactoseFree] = useState(false);
  const [isVegan, setIsVegan] = useState(false);
  const [isVegetarian, setIsVegetarian] = useState(false);

  const saveFilters = useCallback(() => {
    const appliedFilters = {
      glutenFree: isGlutenFree,
      lactoseFree: isLactoseFree,
      vegan: isVegan,
      vegetarian: isVegetarian,
    };

  }, [isGlutenFree, isLactoseFree, isVegan, isVegetarian]);

  useEffect(() => {
    navigation.setParams({
      save: saveFilters,
    });
    console.log('useEffect : ', props); //log-1 attached below
  }, [saveFilters]);

  return (
    <View style={styles.screen}>
      <Text style={styles.title}>Available Filters / Restrictions</Text>
      <FilterSwitch
        label="Gluten-Free"
        state={isGlutenFree}
        onChange={newValue => setIsGlutenFree(newValue)}
      />
      <FilterSwitch
        label="Lactose-Free"
        state={isLactoseFree}
        onChange={newValue => setIsLactoseFree(newValue)}
      />
      <FilterSwitch
        label="Vegan"
        state={isVegan}
        onChange={newValue => setIsVegan(newValue)}
      />
      <FilterSwitch
        label="Vegetarian"
        state={isVegetarian}
        onChange={newValue => setIsVegetarian(newValue)}
      />
    </View>
  );
};

log-1

{
    "navigation": {
        "addListener": [Function addListener
        ],
        "canGoBack": [Function canGoBack
        ],
        "closeDrawer": [Function anonymous
        ],
        "dangerouslyGetParent": [Function dangerouslyGetParent
        ],
        "dangerouslyGetState": [Function anonymous
        ],
        "dispatch": [Function dispatch
        ],
        "goBack": [Function anonymous
        ],
        "isFocused": [Function isFocused
        ],
        "jumpTo": [Function anonymous
        ],
        "navigate": [Function anonymous
        ],
        "openDrawer": [Function anonymous
        ],
        "pop": [Function anonymous
        ],
        "popToTop": [Function anonymous
        ],
        "push": [Function anonymous
        ],
        "removeListener": [Function removeListener
        ],
        "replace": [Function anonymous
        ],
        "reset": [Function anonymous
        ],
        "setOptions": [Function setOptions
        ],
        "setParams": [Function anonymous
        ],
        "toggleDrawer": [Function anonymous
        ]
    },
    "route": {
        "key": "Filters Meals-7XbV4LEyLo",
        "name": "Filters Meals",
        "params": {
            "save": [Function anonymous
            ]
        }
    }
}

log-2

{
    "navigation": {
        "addListener": [Function addListener
        ],
        "canGoBack": [Function canGoBack
        ],
        "closeDrawer": [Function anonymous
        ],
        "dangerouslyGetParent": [Function dangerouslyGetParent
        ],
        "dangerouslyGetState": [Function anonymous
        ],
        "dispatch": [Function dispatch
        ],
        "goBack": [Function anonymous
        ],
        "isFocused": [Function isFocused
        ],
        "jumpTo": [Function anonymous
        ],
        "navigate": [Function anonymous
        ],
        "openDrawer": [Function anonymous
        ],
        "removeListener": [Function removeListener
        ],
        "reset": [Function anonymous
        ],
        "setOptions": [Function setOptions
        ],
        "setParams": [Function anonymous
        ],
        "toggleDrawer": [Function anonymous
        ]
    },
    "route": {
        "key": "Filters-6CuzlMQv2w",
        "name": "Filters",
        "params": undefined,
        "state": {
            "index": 0,
            "key": "stack-7UXVGRjyv-",
            "routeNames": [Array
            ],
            "routes": [Array
            ],
            "stale": false,
            "type": "stack"
        }
    }
}
4

4 Answers

3
votes
onPress={() => console.log(props)}

Replace this

onPress={route.params?.save}

React navigation 4x , No more getParam

navigation.getParam('someParam', 'defaultValue');

is equivalent to:

route.params?.someParam ?? 'defaultValue';

Documentation react navigation official

1
votes

In React-navigation v5 you have to set and get params like this

// your navigation.js should be

    const FiltersNavigator = props => {
  return (
    <screen.Navigator initialRouteName="Filters">
      <screen.Screen
        name="Filters Meals"
        component={FiltersScreen}
        options={({route, navigation}) => ({
          title: 'Filters',
          headerRight: () => (
            <View>
              <TouchableNativeFeedback>
                <MaterialCommunityIcons
                  name="content-save"
                  color="white"
                  size={28}
                  style={{padding: 15}}
                  onPress={() => route.params.save()} 
                />
              </TouchableNativeFeedback>
            </View>
          ),

         })}

      />
    </screen.Navigator>
  );
};

// Your FiltersScreen Component Should be

const FiltersScreen = props => {
  const {navigation} = props;
  const [isGlutenFree, setIsGlutenFree] = useState(false);
  const [isLactoseFree, setIsLactoseFree] = useState(false);
  const [isVegan, setIsVegan] = useState(false);
  const [isVegetarian, setIsVegetarian] = useState(false);

  const saveFilters = useCallback(() => {
    const appliedFilters = {
      glutenFree: isGlutenFree,
      lactoseFree: isLactoseFree,
      vegan: isVegan,
      vegetarian: isVegetarian,
    };

  }, [isGlutenFree, isLactoseFree, isVegan, isVegetarian]);

  useEffect(() => {
    navigation.setParams({save: saveFilters});
  }, [saveFilters]);

  return (
    <View style={styles.screen}>
      <Text style={styles.title}>Available Filters / Restrictions</Text>
      <FilterSwitch
        label="Gluten-Free"
        state={isGlutenFree}
        onChange={newValue => setIsGlutenFree(newValue)}
      />
      <FilterSwitch
        label="Lactose-Free"
        state={isLactoseFree}
        onChange={newValue => setIsLactoseFree(newValue)}
      />
      <FilterSwitch
        label="Vegan"
        state={isVegan}
        onChange={newValue => setIsVegan(newValue)}
      />
      <FilterSwitch
        label="Vegetarian"
        state={isVegetarian}
        onChange={newValue => setIsVegetarian(newValue)}
      />
    </View>
  );
};

If you still having problem you can refer this repo GitHub Repo

Happy Coding ;-)

0
votes

In the second line of the FilterNavigator, put

const { save } = props.route.params;

then further down

onPress = {save}
0
votes

i am also working on same project from udemy,so i have the same error....

replace this

onPress={route.params?.save}

as above comment mentioned by SH Developer

Reasons:

As you open the screen route.params.save is not rendered.Its rendered once the page is open ,still then u get undefined.

If you want to check how this works

step 1: on opening you get undefined error(route.params.save)

step 2: change to route.params or console.log(route.params.save),hence filters page will open.

step 3: change back route.params or (any message) back to route.params.save ,as already filters page is open, its no more shows undefined.