Charles Pettis
Charles Pettis

Reputation: 357

Context is not updating text in React Native after state change

I have a real doozy here and I can't wrap my head around it.

I have this component:

<TouchableOpacity
  onPress={() => {
    if (myContext.value) {
      alert('true');
      //changes myContext.value to false
    } else {
      alert('false');
      //changes myContext.value to true
    }
  }}>
  <Text>{myContext.value ? 'working' : 'not working'}</Text>
</TouchableOpacity>

The weird thing that I don't understand is that the context IS changing the onPress function. So if I click the button it will alert true at first and then false and back and forth as expected. What's not changing is the text that should be going between "working" and "not working".

This component is definitely within the scope of my Provider. I'm using useContext to get access to myContext.

Does anyone know why this might be happening?

Upvotes: 0

Views: 361

Answers (1)

Kartikey
Kartikey

Reputation: 5002

The point to be noted here is that just changing myContext.value = false or true Will not trigger a re-render.

I am not sure how are you handling the value change, But I've created a replica of what you want

Check out this Snack to see the working example.

Create a Context as shown below

import { createContext } from 'react';

const MyContext = createContext();

export default MyContext;

An example App.js component would look like

import * as React from 'react';
import { Text, View, TouchableOpacity } from 'react-native';

import Constants from 'expo-constants';
import MyContext from './MyContext';

import MyComponent from './MyComponent';

export default function App() {
  const [value, setValue] = React.useState(true);

  return (
    <MyContext.Provider value={{ value, setValue }}>
      <MyComponent />
    </MyContext.Provider>
  );
}

And your component where you want to perform this operation should look like this

import * as React from 'react';
import { Text, View, StyleSheet, TouchableOpacity } from 'react-native';
import Constants from 'expo-constants';
import MyContext from './MyContext';

export default function MyComponent() {
  const myContext = React.useContext(MyContext);

  return (
    <TouchableOpacity
      onPress={() => {
        if (myContext.value) {
          alert('true');
          myContext.setValue(false);
          //changes myContext.value to false
        } else {
          alert('false');
          myContext.setValue(true);
          //changes myContext.value to true
        }
      }}>
      <Text>{myContext.value ? 'working' : 'not working'}</Text>
    </TouchableOpacity>
  );
}

Upvotes: 2

Related Questions