Home > Mobile >  React Native - useContext not working with useState (setProviderId is not a function)
React Native - useContext not working with useState (setProviderId is not a function)

Time:05-05

So I'm trying to pass on setProviderId through React Context but when I try to change it through setProviderId(pid) it returns an error stating that setProviderId is not a function, setProviderId is undefined:

ERROR TypeError: setProviderId is not a function. (In 'setProviderId(pid)', 'setProviderId' is undefined)

App.js:

export const ProviderContext = createContext(() => {});
export default function App() {
const [providerId, setProviderId] = useState(`0`);
  return (
     <ProviderContext.Provider value={setProviderId}>
         <ShowScreen />
     </ProviderContext.Provider>
  );
}

ShowScreen.js:

import ProviderContext from '../../../../App.js';

export const ShowScreen = () => {
    const setProviderId = useContext(ProviderContext);
    const pid = '1';
    return(
      <Button onPress={() => {
          setProviderId(pid);
        }} title="Press Me"/>
    );
}

CodePudding user response:

You are doing wrong pass of value value={setProviderId} it must be {{setProviderId}} , but related with this article Caveats , will be good that you define in the component

const state = {
  setProviderId,
  providerId,
}

then pass it to provider like this value={ state }

CodePudding user response:

As mentioned in one of the comments on my original question. I was using:

import ProviderContext from 'App.js';

which imported default app component so all I had to do was change it to:

import { ProviderContext } from 'App.js';
  • Related