Context API: using a function in the context's state to change a context variable. Function isn't exectuing

Refresh

March 2019

Views

29 time

1

-react 16.5 -Although I think this question is a react question and not a react native question, here is my react-native version. My package.json doesn't have a react-native version but instead has: "react-native": "https://github.com/expo/react-native/archive/sdk-32.0.0.tar.gz"

Goal: Change the value of a variable in the context(Context API) from another file

Approach: I have a function in the context to toggle a value and a button in another file that calls it.

Problem: When I fire the button, the function doesn't execute. This happens despite my context variable (called 'ctx') being available in the scope that it is called.

Here is the context which is in it's own file(we will call this the "context file"):

class ConfigProvider extends Component {
  state = {
    dataSource: ds.cloneWithRows(game_array),

    toggleQuestion: () => {
      debugger;
      new_game_array = game_array[0].questions.completed = true;
      this.setState({ game_array: new_game_array });
    }
  };

Here is where it the function is called(we will call this the "button file"):

if (hold_type === "true_false"){
                debugger;
                return(
                    <View style={{ width: dims.width, height: HEIGHT_OF_true_false_SECTION, flexDirection: "row", justifyContent: "space-around", alignItems: "center"}}>
                            <Button title='True!' color='red' onPress={()=>{ctx.toggleQuestion)}} />
                            <Button title='False' color='green' onPress={()=>{}} />
                    </View>
                )

            }

MY EXPERIENCE

When the Button File comes to the debug statement, I can inspect the variable "ctx", and it is fully available(including ctx.toggleQuestion). However, the function doesn't fire because the debug statement in the context file isn't caught.

HOW YOU CAN HELP ME: -explain why it isn't caught -tell me if my approach will work or wont work -If you know of a better approach, please say so.

Thanks

1 answers

0

OK if you can see ctx.toggleQuestion in the inspector, the error is that (unless you have a typo...)

onPress={()=>{ctx.toggleQuestion)}} (this line doesnt actually call the function. In fact it doesn't do anything)

should be

onPress={()=>{ctx.toggleQuestion()}}