简体   繁体   中英

How do I update an object's state keeping the existing elements using useState hook?

I have an array of objects:

// seedColors.js

export default [
  {
    paletteName: "Material UI Colors",
    colors: [
      { name: "red", color: "#F44336" },
      { name: "pink", color: "#E91E63" },
    ]
  },
  {
    paletteName: "Flat UI Colors v1",
    colors: [
      { name: "Turquoise", color: "#1abc9c" },
      { name: "Emerald", color: "#2ecc71" },
    ]
  }
]

In my app.js file, I'm creating a new array of object, how would I append the new object to the existing object using useState hook?

// app.js

import seedColors from "./seedColors";

function App() {
  const [palettes, setPalettes] = useState({ palettes: seedColors });

  const savePalette = (newPalette) => {
    // newPalette = { paletteName: "New Test Palette", colors: [{ color: "blue", name: "blue" }] };
    setPalettes({ ...palettes, palettes: newPalettes });
  };

This isn't updating the original object state, instead it is crashing the application

I would want the state to be updated to:

[
  {
    paletteName: "Material UI Colors",
    colors: [
      { name: "red", color: "#F44336" },
      { name: "pink", color: "#E91E63" },
    ]
  },
  {
    paletteName: "Flat UI Colors v1",
    colors: [
      { name: "Turquoise", color: "#1abc9c" },
      { name: "Emerald", color: "#2ecc71" },
    ]
  },
  { 
    paletteName: "New Test Palette", 
    colors: [
      { color: "blue", name: "blue" },
    ] 
  },
]

Your application is likely "crashing" because you have a typo:

 setPalettes({ ...palettes, palettes: newPalettes });
 //                                             ^

You don't have a variable with name newPalettes . But even if you fix that, it doesn't produce the result you want.

Is there a reason you are setting the state to be an object with a single property? If not, just assign the array directly (which seems to be what you want based on your description of what you want the state to look like):

const [palettes, setPalettes] = useState(seedColors);

Then you can update the array with

setPalettes([...palettes, newPalette]);

If you need that object, then it would be:

setPalettes({...palettes, palettes: [...palettes.palettes, newPalette]});

You declared const [palettes, setPalettes] = useState({ palettes: seedColors });
but you try to save as setPalettes({...palettes, palettes: newPalettes });

I would suggest to save them as on object:

const [palettes, setPalettes] = useState(seedColors);
setPalettes({ ...palettes, newPalettes });`

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM