0

Instead of merging changes I make to a state object, React is overwriting it completely.

Could this be caused by the context? I'm not sure if I can pass a dispatch event directly as a prop. I've tried wrapping setParams in another function, like in the "lifting state up" docs, however to no effect.

Expected Output

{width: 400, height: 400, strokeWeight: 0.25, color: "#d9eb37", resolution: 10}

Current Output

{color: "#d9eb37"}

React context holds the state

const Context = createContext();

const Provider = ({ children }) => {
  const [params, setParams] = useState({
    width: 400,
    height: 400,
    strokeWeight: 0.25,
    color: "#ad3e00",
    resolution: 10
  });

  return (
    <Context.Provider value={{ params, setParams }}>
      {children}
    </Context.Provider>
  );
};

Generic input component

const Input = () => {
  const { params, setParams } = useContext(Context);

  render(
    <input
        type="color"
        value={params.color}
        onChange={(e) => setParams({ color: e.target.value })}
      />
  );
}
msalla
  • 717
  • 6
  • 23
  • 1
    That's how `useState` works. It replaces the value, it does not do any merging. That's on you to do – Dominik Dec 04 '20 at 00:21
  • I'd recommend using the [functional update form](https://reactjs.org/docs/hooks-reference.html#functional-updates) of `setParams` for setting state (mentioned only in comments and non-accepted answers on the linked question above). – Henry Woody Dec 04 '20 at 00:25

1 Answers1

3

useState does not merge state like setState in class component, you have to do the job on your own.

onChange={(e) => setParams((params)=>({ ...params, color: e.target.value }))}

boaol
  • 108
  • 1
  • 6