Kevin Powell - CommunityKP-C
Kevin Powell - Communityβ€’2y agoβ€’
10 replies
ananthukrish

state not updating properly

import React, { useState } from "react";
import "../styles/App.css";
const App = () => {
  const [shapes, setShapes] = useState([]);

  const addShape = (e) => {
    e.preventDefault();
    const form = e.target;
    const formData = new FormData(form);
    const shape = formData.get("selectShape");
    const newShape = {
      shape: shape,
    };
    setShapes([...shapes, newShape]);
    console.log(shapes);
  };

  return (
    <div id="main">
      <div id="shape-creator">
        <form onSubmit={addShape}>
          <select defaultValue="Square" name="selectShape">
            <option value="Square">Square</option>
            <option value="Circle">Circle</option>
          </select>
          <button type="submit">Add Shape</button>
        </form>
      </div>
      <div id="shapes-holder">
        {/* {shapes.map((shape, index) => (
          <Shape key={index} type={shape.type} id={shape.id} />
        ))} */}
      </div>
    </div>
  );
};

on the first form, submission setShapes not getting updated. But the second form submission is updated by the previous value why is this happening?
Was this page helpful?