Search code examples
reactjstypescriptreact-context

Updating an object via context in react


I am struggling to declare context with typescript and react. According to the react documentation, you can pass your setEconomy action to the EconomyContext.Provider component. However, the value tag on that component will only accept economy as input and not as declared below an object { economy, setEconomy }.

How can I declare my state with the option to update the state in a nested component?

import React, { createContext, useState } from 'react';
import Economy from './model/Economy';

const defaultEconomy: Economy = {
    households: [],
    simulationId: '',
};
export const EconomyContext = createContext<Economy>(defaultEconomy);

export const ContextProviders: React.FC<React.PropsWithChildren> = (props) => {
    const [economy, setEconomy] = useState(defaultEconomy);
    return <EconomyContext.Provider value={{ economy, setEconomy }}>{props.children}</EconomyContext.Provider>;
};

Solution

  • createContext<Economy>(defaultEconomy)
    

    When you created the context, you told typescript that the value would be an Economy. But then when you try to provide the value later on, you're passing in a more complex object, which has both an economy property and a setEconomy property. To do that, create your context something like this:

    export const EconomyContext = createContext<{
      economy: Economy;
      setEconomy: (newEconomy: Economy) => void;
    }>({ 
      economy: defaultEconomy, 
      setEconomy: () => {} 
    });