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

cannot change usestate to change the state of the components

This is code of my AddBlog Component

import React, { useState } from "react";

function AddBlogs() {

const[state, setState] = useState({blogs:[]})


const AddAnother = () => {
    return (
        <div>
            <label>Topic</label>
            <input></input>
            <button onClick={addblog}>Add another topic</button>
        </div>
    );
}

const addblog = () =>{
    setState({
        blogs:[...state.blogs,<AddAnother></AddAnother>]
    });
    console.log("Hello");
}

return (
    <div>
        <form>
            
            <div>
                <label>Topic</label>
                <input></input>
                <button onClick={addblog}>Add another topic</button>
            </div>
            <div>
                {state.blogs}
            </div>
        </form>
    </div>
);
}
export default AddBlogs;

When I click that Add another topic button AddAnother components blinks for just 0.5 second or less. Any solution for this?

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

>Solution :

I see a couple things that will cause problems. First, when you update state, you shouldn’t use the current state. Instead, you should use the setState that accepts a function with the old state as the first parameter, such as the following:

const addblog = () => {
    setState((oldState) => {
        return { blogs: [...oldState.blogs, <AddAnother />] };
    });
    console.log("Hello");
};

This won’t solve your problem, though. The issue you’re seeing is due to you not having a key in your array of components. So try this:

const addblog = () => {
    setState((oldState) => {
        return { blogs: [...oldState.blogs, <AddAnother key={oldState.blogs.length} />] };
    });
    console.log("Hello");
};

As David pointed out, the form is also posting, which is causing part of the problem as well.

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