gen.dev
gen.dev

Reputation: 25

React push object into array and map error map not a function

I have an array that has initially 2 values, when I click on the add button I want to add a new object but then it tells me map is not a function. Any help is greatly appreciated. This is not my entire component but what you would need to replicate:

const Equipments = (props) => {

const [equipment,setEquipment]=useState([1,2]);

const addEq =  ( ) => {
console.log('add eq')
var id = equipment.length+1;
setEquipment(equipment.push(id));
console.log('this is the id',id, 'this is the array',equipment)
};


const renderEQForm = (equipment, index) => {
  return (
    <>    
           <label>{equipment.id}</label>
            <Form.Item
              name={['payments', 'method']}
              label="Method:"
              defaultValue = 'Credit Card'>
               <Select  defaultValue = 'Credit Card'>
                 <Option value='Cash'>Cash</Option>
                 <Option value='Check'>Check</Option>
                 <Option  value='Credit Card'>Credit Card</Option>
                 <Option value='Google Pay'>Google Pay</Option>
               </Select>
             </Form.Item>
             <Form.Item
                 
                  name={["equipment", 'brand']}
                  rules={[{ required: false, message: 'Missing brand' }]}
                  label='Brand:'
                >
                  <Input placeholder="Brand" />
                </Form.Item>

                </>
                
  )}

 return (
    <>
      
      {equipment.map(renderEQForm)}
      <button onClick={()=>addEq()}>Add</button>
    </>
    );
    };


export default Equipments

Upvotes: 1

Views: 1722

Answers (2)

jean182
jean182

Reputation: 3505

Don't use push because that is mutating the array, when you want to change the state of your code copy the existing array and mutate that one, for example using the spread syntax will do what you want

const addEq =  ( ) => {
 console.log('add eq')
 const id = equipment.length+1;
 // This returns a new array with the current equipment items plus the new id.
 setEquipment([...equipment, id]);
console.log('this is the id',id, 'this is the array',equipment)
};

Is worth to notice that the error you're getting is because push returns the new array length(a number) so setting that in the setEquipment would make your equipment a number and map is not a function included in the number object.

Upvotes: 0

Rostyslav
Rostyslav

Reputation: 2856

The problem is in this line

setEquipment(equipment.push(id));

equipment.push(id) returns a number NOT an array. Therefore, your state gets set to a Number which doest not have .map function in its prototype.

Your solution is

setEquipment([...equipment, id]);

Upvotes: 1

Related Questions