Search code examples
javascriptreactjsuse-state

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?


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.