0

In my code, I have this method called addToArray declared in my App.js file and passed to react context via state like so: App.js

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      // init values
      array: [],
      ...
      removeFromArray: () => this.removeFromArray(),

      ...
    }
  }
  fetchArray = async () => {
      ...
      this.setState({ array: result });


    } catch (e) {
      alert('Error occured and nothing could be fetched');
    }
  }
  }
  componentDidMount() {
    this.fetchArray();
    ...
  }
    ...

  removeFromArray = (id) => {
    ...
    alert(id);
  }
  render() {
    // variables to init contexts with
    const {
      array,
      removeFromArray
    } = this.state;

    return (
      <GlobalContext.Provider value={{
        array,
        removeFromArray
      }} >
          <Routes />
      </GlobalContext.Provider>
    );
  }
}

The context is declared like this: Context.js

export const GlobalContext = React.createContext({
 array: [],
 removeFromArray: () => { } 
});

and is called like this:

 const btn = (props) => {
      const GlobalCtx = useContext(GlobalContext);
      return(
        <View style={card.editOpacity}>
         <Icon
           name="minus-circle"
           type='font-awesome'
           color='red'
           onPress={() => {
             GlobalCtx.removeFromArray(props.id)
            }} />
          <Text style={card.header}>{props.title}</Text>
         </View>
      );

for some reason it is not working, but I think it may have to do with the parameters and the way it's being passed to the context.

1 Answer 1

1

There is no need to put the removeFromArray function inside state. You can render your provider like this

<GlobalContext.Provider value={{
  array,
  removeFromArray: this.removeFromArray
}}>
  <Routes />
</GlobalContext.Provider>

Also it's not clear what it this.removeFromGutka() in the function that you have added to the state.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! That fixed it. About the removeFromGutkas() function, it was a mistake in copying from the codebase.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.