Search code examples
javascriptreactjsreact-reduxexporeact-context

React Native Context setUser is not a function


I am trying to use React Context to manage if the user is signed in or not. What I have so far is something like this:

import AuthUserContext, { AuthUserProvider } from './Components/auth/AuthUserProvider';

function App() {
  const {user, setUser} = React.useContext(AuthUserContext)
  setUser('') // SetUser is not a function
}

App.tsx

import React, { useState, createContext } from 'react';
var user: any, setUser: any;

const AuthUserContext = React.createContext({user, setUser});
export default AuthUserContext;

export const AuthUserProvider = ({ children } : {children: any}) => {
  const [user, setUser] = useState(null);
  
  return (
    <AuthUserContext.Provider value={{ user, setUser }}>
      {children}
    </AuthUserContext.Provider>
  );
};

AuthUserProvider.tsx

Here's the error:

TypeError: setUser is not a function. (In 'setUser('')', 'setUser' is undefined)

This error is located at:
    in App (created by ExpoRoot)
    in ExpoRoot (at renderApplication.js:45)
    in RCTView (at View.js:34)
    in View (at AppContainer.js:106)
    in DevAppContainer (at AppContainer.js:121)
    in RCTView (at View.js:34)
    in View (at AppContainer.js:132)

I'm new to react native and have been trying to fix this for hours. Any help is appreciated. Thank you so much!


Solution

  • Issue

    It seems the initial value of your context is undefined.

    var user: any, setUser: any;
    
    const AuthUserContext = React.createContext({ user, setUser }); // both undefined
    

    Solution

    Define the shape of the context.

    var user: any, setUser: any;
    
    const AuthUserContext = React.createContext({
      user: '',
      setUser: () => {}, // <-- indicate setUser is a function
    });
    

    See Updating Context from a Nested Component