0

My current context with a method to set the updated context looks like this:

export const AppContextProvider = ({ children }) => {
  const [currentAppContext, setCurrentAppContext] = useState(initApp)

  const setAppContext = values => {
    setCurrentAppContext(values)
  }

  return <AppContext.Provider value={{ appContext: currentAppContext, setAppContext }}>{children}</AppContext.Provider>
}

and I set the new context in a component like so:

export default function Settings() {
  const { appContext, setAppContext } = useContext(AppContext)

  const func = ({ accountId }) => {
      setAppContext({
        ...appContext,
        accountId: accountId,
      })
    },
  })
  return <></>
}

But I would prefer to do just setAppContext((currentContext) => ({...currentContext, accountId: accountId})) like we do in the useReducer hook useReducer(state => state.item) kind of thing. Is this possible, if so, how would I write it?

Kevin Danikowski
  • 4,620
  • 6
  • 41
  • 75
  • Does this fit your demand? Just provide `dispatch` from `React.useReducer` rather than `setState`? – keikai Aug 31 '20 at 16:11

1 Answers1

0

The set function returned from useState() allows you to pass a function in just like this, so actually no change to my code was necessary to allow this to happen, it already works!

Kevin Danikowski
  • 4,620
  • 6
  • 41
  • 75