javascriptreactjsarraysreact-hooksarray.prototype.map

add new user namesList.map


here his code give me undefind i want add a new user to the name list I don't know where is the problem

there is cardList component

import React from 'react';
import Card from '../Card/Card';

const CardList = ({ namesList, deleteFunc }) => {
    console.log(namesList);
    const cards = namesList?.map(({ id, ...otherProps }) => {
        return <Card key={id} id={id} {...otherProps} deleteFunc={deleteFunc}></Card>;
    });
    return <div>{cards}</div>;
};

export default CardList;

there is card component

import React from 'react';
import styles from './card.module.css';

const Card = ({id, name, age, phone, address, type, deleteFunc}) => {
    return (
        <div className={styles.card} style={{ backgroundColor: type === "girl" ? "pink" : "blue" }}>
            <div>Name : {name}</div>
            <div>Age : {age}</div>
            <div>phone : {phone}</div>
            <div>Address : {address}</div>
            <div>type : {type}</div>
            <div className={styles.deleteBtn} onClick={(e) => deleteFunc(e, id)}>X</div>
        </div>
    );
};

export default Card;

Solution

  • There is a problem with your handler where setState is called twice.

    Corrected Code:

    const addNewUserHandler = (data) => {
        setState((prevState) => ([...prevState, data]));
    };