Chris Westbrook
Chris Westbrook

Reputation: 2110

React Context value never updates

I have the following code as a component that returns a context. For some reason when I call the updateUser function it is not setting the state, I keep getting a blank object. Is there something different I have to do to a function like that when it has parameters?

import React, { useState } from "react";
const UserContext = React.createContext({
  user: {},
  updateUser: (incomingUser) => {},
});
const UserData = (props) => {
  const [user, setUser] = useState({});

  const updateUser = (incomingUser) => {
    setUser(incomingUser);
    console.log(`user=${JSON.stringify(incomingUser)}`);
  };

  return (
    <UserContext.Provider value={{ user, updateUser }}>
      {props.children}
    </UserContext.Provider>
  );
};
export { UserData, UserContext };

Upvotes: 2

Views: 212

Answers (1)

lawrence-witt
lawrence-witt

Reputation: 9364

Get rid of the default value for UserContext, or initialise it as null:

const UserContext = React.createContext(null);

Per the React Docs:

When React renders a component that subscribes to this Context object it will read the current context value from the closest matching Provider above it in the tree.

The defaultValue argument is only used when a component does not have a matching Provider above it in the tree. This default value can be helpful for testing components in isolation without wrapping them.

Upvotes: 1

Related Questions