2

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 };

1 Answer 1

1

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.

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

Comments

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.