Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

when i click to the button the state change but the render still the same

i want to add new links every time i click on button
i use first useState like this :

 const [links, setLinks] = useState([
    {
      number: 1,
      platforms: null,
      url: null,
    },
  ]);

then handleClick function every time i click on button :

 const handleclick = () => {
    let addLinks = links;
    const newLink = {
      number: links.length + 1,
      platforms: null,
      url: null,
    };
    addLinks.push(newLink);
    return  setLinks(addLinks);
  };

in the runder :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  <h1>Customize your links</h1>
  <p>
    Add/Edit/Remove links and then share all your profiles with the world
  </p>
  
    <button
      type="button"
      class="btn btn-outline-danger "
      style={{ border: "1px solid #a009e4", color: "#a009e4" }}
      onClick={handleclick}
    >
      + Add New Link
    
  
  
    {links.map((link)=>{
       return (
            <AllLinks number={link.number} key={link.number}/>
       );
     })}

i try useEffect but still the same problem the value of state (links) is changed but in the browser nothing added

>Solution :

When you assign one variable to another (let addLinks = links;), you don’t copy the array, just the reference to the original array. To shallow copy the array use spread: let addLinks = [...links];.

Since you’re also creating a new state based on the previous one, you should use an updater function. Take the prevLinks, spread it into a new array, and add the new link:

const handleclick = () => {
  setLinks(prevLinks => [ // create a new array
    ...prevLinks, // add the previous links
    { // add the new link
      number: links.length + 1,
      platforms: null,
      url: null,
    }
  ])
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading